James Kang
James Kang

Reputation: 35

How to create HashMap out of Set, using streaming in Java

Set<Integer> ageSet = new HashSet<>();
Map<Integer, People> map = new HashMap<>();

for(int age : ageSet{
    People people = new People(age);
    map.put(age, people);
}

I'm trying to create an instance and put it in Hashmap with its integer. If I would like to code this using parallelStream()(stream()), how could I do this?

Upvotes: 0

Views: 64

Answers (3)

MrsNickalo
MrsNickalo

Reputation: 217

Refer to this example using a student and id:

    //set of ids
    Set<Integer> idSet = new HashSet<>();
    //populate some ids
    for(int i=0; i<5; i++)
    {
        idSet.add(i);
    }
    //create map
    Map<Integer, Student> studentMap = new HashMap<>();
    //stream id list to map with students
    idSet.stream().forEach(id -> studentMap.put(id, new Student(id)));
    //print out
    System.out.println(studentMap);

Upvotes: 0

Eng.Fouad
Eng.Fouad

Reputation: 117587

You can collect the stream by usng Collectors.toMap(keyMapper, valueMapper):

Map<Integer, Person> map = ageSet.stream()
                                 .collect(Collectors.toMap(Function.identity(), Person::new));

Upvotes: 3

Ryan
Ryan

Reputation: 1760

I'm assuming your People class has a getAge() function.

Map<Integer, People> map = ageSet.stream()
                                 .map(a -> new People(a))
                                 .collect(Collectors.toMap(People::getAge, p -> p));

Upvotes: 4

Related Questions