问题描述
我有A类
Company {
String name;
Logo logo;
}
Logo {
int color; //can have values=1 (green),2 (red),3 (blue) ...
String name;
String address;
}
需要的输出:对于每种类型1,2,3,按颜色对Logo的所有实例进行分组.对于每个这样的组,什么是A.id给我公司以其颜色徽标.例如.哪些公司的徽标为红色?
Output needed : for each type 1,2,3 Group all instances of Logo by color. For each such group what were A.idGive me companies by their color logos.E.g. which companies have logo red?
我尝试关注
Input
List<Company> company = {//initialization}
company.stream().map(e -> e.getLogo())
.collect(Collectors.groupingBy(e -> {Logo b = new Logo();
b.setType(e.getType();
return b;}, Collectors.counting()))
这将产生一个徽标图并进行计数.如何获得公司名称?
This produces a map of Logo and count How do I get names of Company?
推荐答案
如果要查找所有logo
为color
的公司,则应将其分组为:
If you were to look for all companies given a color
of their logo
, you shall group as:
Map<Integer, List<Company>> collect = company.stream()
.collect(Collectors.groupingBy(e -> e.getLogo().getColor()));
以防万一,只是这些值的计数是无光泽的,然后应使用Collectors.counting
,例如:
Just in case, just the count of such values matte, you should then use Collectors.counting
such as:
Map<Integer, Long> count = company.stream()
.collect(Collectors.groupingBy(e -> e.getLogo().getColor(),
Collectors.counting()));
简而言之,如果您希望值本身为Company
类型,请不要map
流.
In short, do not map
the stream if you want the values to be of type Company
itself.
编辑:基于注释,如果您打算将Company
转换为其name
,则可以将其分组后进行映射.使用Collectors.mapping
如:
Edit: Based on comments, if the idea is to convert Company
to its name
you can map once grouped. Using Collectors.mapping
such as :
Map<Integer, List<String>> collect = company.stream()
.collect(Collectors.groupingBy(e -> e.getLogo().getColor(),
Collectors.mapping(Company::getName, Collectors.toList())));
这篇关于如何按Java 8分组并从父级收集ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!