【问题标题】:How to group by property values from object java如何按对象java中的属性值分组
【发布时间】:2020-06-18 13:29:15
【问题描述】:

假设我有一个下面的对象,

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

以及上述类的值,

 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 值和地图类型的属性与其他属性分组"

请帮我解决这个问题

【问题讨论】:

    标签: java arraylist java-stream


    【解决方案1】:

    首先连接每个列表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())));
    

    【讨论】:

    • .distinct() 操作在这里显得多余
    • @Naman firstsample1 中出现了 2 次,也许这就是原因
    猜你喜欢
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 2022-03-17
    • 1970-01-01
    • 2021-11-25
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多