创建地图<string,list <integer =“”>&gt;来自String [] []使用java 8流

时间:2018-04-22 23:11:21

标签: java-8

我可以使用增强的for循环和地图的computeIfAbsent进行创建,如下所示。

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

有没有什么方法可以使用 stream 和collectors api一起构建地图?

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

3 个答案:

答案 0 :(得分:1)

试试这个。

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

答案 1 :(得分:1)

您可以尝试这样

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

答案 2 :(得分:1)

使用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())));

使用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;}));