繁体   English   中英

如何按 object java 中的属性值分组

[英]How to group by property values from object java

假设我有一个下面的 object,

class sample
{
private String type;
private List<String> a1;
private List<String> a2;
private List<String> a3;
}

和以上 class 的值,

 Sample sample1 = new Sample("type1", Arrays.asList("first", "second"), Arrays.asList("first") , [] );
 Sample sample2 = new Sample("type2", Arrays.asList("first", "second"), Arrays.asList("third") , [] );

我期待下面的结果,

first - [ type1, type2 ], second -[ type1, type2 ], third - [ type2 ]

要求:“将 a1、a2、a3 值和 map 类型的属性与其他属性分组”

请帮我解决这个问题

首先连接每个列表 a1、a2 和 a3,将其映射到Map.entry ,其中键是列表中的字符串,值是type (使用distinct ,因为有时“first”同时出现在列表 a1 和 a2 中)。 然后使用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())));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM