在 Java 8 中使用流减少 bean 列表

假设您有一个 bean 数组列表,具有几个属性:


class Item {

    public int id;

    public String type;

    public String prop1;

    public String prop2;

    public String prop3;

}

您有一个包含以下值的列表:


id | type| prop1| prop2| prop3

1  | A   | D    | E    | F

1  | B   | D    | E    | F

2  | A   | G    | H    | I

2  | B   | G    | H    | I

2  | C   | G    | H    | I

我想将其简化为包含以下内容的列表:


id | type    | prop1| prop2| prop3  

1  | A, B    | D    | E    | F

2  | A, B, C | G    | H    | I

请注意,对于相同的 id,除了类型之外,实例属性具有完全相同的值。


有没有办法使用流来做到这一点?


暮色呼如
浏览 193回答 1
1回答

湖上湖

首先,将集合分组Item::getId并将结果保存到Map<Integer, List<String>>. 其次,将每个条目变成一个项目并将它们收集在结果列表中。List<Item> result = list&nbsp; &nbsp; .stream()&nbsp; &nbsp; // build a Map<Integer, List<String>>&nbsp; &nbsp; .collect(Collectors.groupingBy(Item::getId, Collectors.mapping(Item::getType, Collectors.toList())))&nbsp; &nbsp; .entrySet()&nbsp; &nbsp; .stream()&nbsp; &nbsp; // transform an entry to an item&nbsp; &nbsp; .map(i -> new Item(i.getKey(), String.join(", ", i.getValue().toArray(new String[0]))))&nbsp; &nbsp; .collect(Collectors.toList());要清理流链,您可以在单独的方法中移动构造逻辑并使用对该方法的引用(例如map(Item::fromEntry):public static Item fromEntry(Map.Entry<Integer, List<String>> entry) {&nbsp; &nbsp; return new Item(&nbsp; &nbsp; &nbsp; &nbsp; entry.getKey(),&nbsp; &nbsp; &nbsp; &nbsp; String.join(", ", entry.getValue().toArray(new String[0]))&nbsp; &nbsp; );}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java