1

I can create with enhanced for loop and with map's computeIfAbsent as below.

String [][] students = {{"David","50"},{"Sherif","70"},{"Bhavya","85"},{"Bhavya","95"}};
Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
for(String student[] : students) {
    map.computeIfAbsent(student[0], (k)->new ArrayList<Integer>()).add(Integer.parseInt(student[1]));
}

Is there any way I can use stream with collectors api to build map as above?

Map<String, List<Integer>> m = Arrays.stream(students)
        .collect(Collectors.?);

3 Answers 3

1

Try this out.

String[][] students = { { "David", "50" }, { "Sherif", "70" }, { "Bhavya", "85" }, { "Bhavya", "95" } };
Map<String, List<Integer>> studentsByName = Stream.of(students).collect(Collectors.groupingBy(kv -> kv[0],
        Collectors.mapping(kv -> Integer.valueOf(kv[1]), Collectors.toList())));
System.out.println(studentsByName);
Sign up to request clarification or add additional context in comments.

Comments

1

You can try like this

map = Arrays.stream(students)
         .map(array->new Pair<String,Integer>(array[0],Integer.valueOf(array[1])))
         .collect(Collectors.groupingBy(p->p.getKey(), Collectors.mapping(p->p.getValue(),
                                        Collectors.toList())));

Comments

1

Using groupingBy:

Arrays.stream(students)
      .map(a -> new AbstractMap.SimpleEntry<>(a[0], Integer.valueOf(a[1])))
      .collect(groupingBy(AbstractMap.SimpleEntry::getKey,
                     mapping(AbstractMap.SimpleEntry::getValue,  
                                    toList())));

Using toMap:

Arrays.stream(students)    
      .map(a -> new AbstractMap.SimpleEntry<>(a[0], Integer.valueOf(a[1])))
      .collect(toMap(AbstractMap.SimpleEntry::getKey, 
                    k -> new ArrayList<>(Collections.singletonList(k.getValue())), 
                             (left, right) -> {left.addAll(right);return left;}));

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.