英文:
Reduce elements in a java list using Java8 streams
问题
我有一个包含如下元素的 Java 列表:
输入列表名称为 itemsList:
List<Items> itemsList;
Items 类:
List<String> Identifier;
List<String> websites;
列表的输入元素:
Identifier    websites
 id1,id2      site1
 id2,id3       site3
 id5           site5
 id1           site6
 id5          site7 
 id6           site8
结果列表:
Identifier         websites
 id1,id2,id3      site1,site3,site6   
 id5                site5,site7
 id6                site8
正如您从结果中看到的:
如果任何行中存在相同的 Identifier,它们应该被合并在一起,所有的 websites 也应该被合并在一起。
以下是我尝试过的方法:
itemsList.stream().reduce((v1, v2) ->
{
    // 检查 Identifier 是否有重叠
    if (!Collections.disjoint(v1.getIdentifier(), v2.getIdentifier())) {
        v1.getIdentifier().addAll(v2.getIdentifier());
        v1.getWebsites().addAll(v2.getWebsites());
    } 
    return v1;
});
我的解决方案效果不太好…它只合并了第一行。
我知道这不是一个容易解决的问题。
英文:
I have a java list that contains elements like below:
Input List name is itemsList:
List<Items> itemsList ;
Items class:
List<String> Identifier;
List<String> websites;
Input Elements for the list:
Identifier    websites
 id1,id2      site1
 id2,id3       site3
 id5           site5
 id1           site6
 id5          site7 
 id6           site8
Result list:
   Identifier         websites
     id1,id2,id3      site1,site3,site6   
     id5                site5,site7
     id6                site8
As you can see from the result :
Identifier should be grouped together if anyone Identifier is present from the other row and all websites should be combined together as well
Here is what I tried :
    itemsList.stream().reduce((v1, v2) ->
    {
        //see if identofier overlaps
        if (!Collections.disjoint(v1.getIdentifier(), (v2.getIdentifier()))) {
            v1.getIdentifier().addAll(v2.getIdentifier());
            v1.getwebsites().addAll(v2.getwebsites());
     
        } 
        return v1;
    });
my solution doesn't help much..As it only reduces the first row.
I know it is not an easy one to solve.
答案1
得分: 2
一个简单的方法:
- 创建一个结果列表,并将其初始化为空。
 - 遍历输入列表。对于每个输入元素:
- 找到结果列表中的所有元素,这些元素包含输入元素的 ID 或站点(或两者皆有)。
 - 将它们合并(缩减)为一个结果列表成员。
 - 同样添加输入元素。
 
 
使用经典循环,不使用流操作。
英文:
A simple approach:
- Create a result list and initialize it to empty.
 - Iterate over the input list. For each input element:
- Find all elements in the result list that holds either an ID or a site (or both) from the input element.
 - Combine (reduce) them into one result list member.
 - Also add the input element.
 
 
Use a classical loop, no stream operation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论