result = list.stream().collect(Collectors.groupingBy(q -> q.getBrand()));
这样分组后,得到的数据结构,key是分组的组名,
我想要的是可以重构这个分组后的数据结构,用myKey:key,myValue:当前组对应的分组的数据
应该怎么一句话写完?因为我现在没办法,只能再写一个循环,来构造这个结构。
伊谢尔伦2017-04-18 10:19:57
You are using groupingBy
一个参数的方法,该方法只能传参一个Function
as the mapping function of Key
But in factCollectors.groupingBy
there are methods with at most three parameters. The other two parameters and one parameter are just overloads of the three-parameter method. So if you want to process grouped Value data, you need to understand the fundamentals. What capabilities does the above three parameter method provide?
Collector<T, ?, M> groupingBy(Function<? super T, ? extends K> classifier,
Supplier<M> mapFactory,
Collector<? super T, A, D> downstream) {
You can see that there are three parameters. The first parameter is the key and it is also a collector. That is to say, these three parameters are actually to solve the grouping problemFunction
了,第二个参数是一个map工厂,也就是最终结果的容器,一般默认的是采用的HashMap::new
,最后一个参数很重要是一个downstream
,类型是Collector
As mentioned before, the second parameter defaults to HashMap::new
, so You can use the
two-parameter method, as you can see below, the second parameter is HashMap::new
HashMap::new
,所以你就可以采用Collectors.groupingBy
两个参数的方法,如下可以看到,第二个参数是HashMap::new
public static <T, K, A, D>
Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier,
Collector<? super T, A, D> downstream) {
return groupingBy(classifier, HashMap::new, downstream);
}
In fact, the third parameter collector of the one-parameter method actually defaults to Collectors.toList
, so the final type returned by what you wrote above is Map<String, List>
Collectors.groupingBy
方法的第三个参数收集器其实默认是Collectors.toList
,所以你上面写的返回最终的类型是Map<String, List>
Student
String type
int score
String name
List<Student> students = new ArrayList<>()
// 每个学生类型的总分数
Map<String, Integer> map1 =
students.stream.collect(Collectors.groupingBy(Student::getType, Collectors.summingInt(Student::getScore))));
// 每个学生类型中的得分最高的那个学生
Map<String, Optional<Student>> map2 = students.stream.collect(Collectors.groupingBy(Student::getType, Collectors.maxBy(Comparator.comparing(Student::getScore))));
Anyway, you can find a lot of third parameter collectors in . If it doesn’t work, you can customize the collector. I hope it can help youCollectors