如何根据对象java中的属性值进行分组
假设我有一个下面的物体如何根据对象java中的属性值进行分组,java,arraylist,java-stream,Java,Arraylist,Java Stream,假设我有一个下面的物体 class sample { private String type; private List<String> a1; private List<String> a2; private List<String> a3; } 我期待下面的结果 first - [ type1, type2 ], second -[ type1, type2 ], third - [ type2 ] 要求: 将a1、a2、a3值和映射类型的属性与其他属
class sample
{
private String type;
private List<String> a1;
private List<String> a2;
private List<String> a3;
}
我期待下面的结果
first - [ type1, type2 ], second -[ type1, type2 ], third - [ type2 ]
要求:
将a1、a2、a3值和映射类型的属性与其他属性分组
请帮助我解决此问题首先对每个列表a1、a2和a3进行处理,将其映射到
映射。输入
,其中键是列表中的字符串,值是类型
(使用distinct
,因为在列表a1和a2中都出现了“First”的情况)。然后使用Map.Entry
进行分组
Sample sample1 = new Sample("type1", Arrays.asList("first", "second"), Arrays.asList("first"), Arrays.asList());
Sample sample2 = new Sample("type2", Arrays.asList("first", "second"), Arrays.asList("third"), Arrays.asList());
List<Sample> samples = Arrays.asList(sample1, sample2);
Map<String, List<String>> samplesMap = samples.stream()
.flatMap(s -> Stream.of(s.getA1(), s.getA2(), s.getA3())
.flatMap(l -> l.stream().map(a -> Map.entry(a, s.getType())))
.distinct()
)
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
sample1=newsample(“type1”,Arrays.asList(“first”,“second”),Arrays.asList(“first”),Arrays.asList());
Sample sample2=新样本(“type2”,Arrays.asList(“第一”,“第二”),Arrays.asList(“第三”),Arrays.asList());
List samples=Arrays.asList(sample1,sample2);
Map samplesMap=samples.stream()
.flatMap(s->Stream.of(s.getA1()、s.getA2()、s.getA3())
.flatMap(l->l.stream().map(a->map.entry(a,s.getType()))
.distinct()
)
.collect(Collectors.groupingBy(Map.Entry::getKey、,
Collectors.mapping(Map.Entry::getValue,Collectors.toList());
操作的.distinct()
请参见中的ems redundanthere@Namanfirst
在sample1
中出现了两次,也许这就是原因
Sample sample1 = new Sample("type1", Arrays.asList("first", "second"), Arrays.asList("first"), Arrays.asList());
Sample sample2 = new Sample("type2", Arrays.asList("first", "second"), Arrays.asList("third"), Arrays.asList());
List<Sample> samples = Arrays.asList(sample1, sample2);
Map<String, List<String>> samplesMap = samples.stream()
.flatMap(s -> Stream.of(s.getA1(), s.getA2(), s.getA3())
.flatMap(l -> l.stream().map(a -> Map.entry(a, s.getType())))
.distinct()
)
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));