0
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?

3 Answers 3

4

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));
Sign up to request clarification or add additional context in comments.

Comments

3

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

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

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.