使用Java8流(streams)来减少Java列表中的元素。

huangapple go评论65阅读模式
英文:

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&lt;Items&gt; itemsList ;

Items class:

List&lt;String&gt; Identifier;
List&lt;String&gt; 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) -&gt;
    {
        //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

一个简单的方法:

  1. 创建一个结果列表,并将其初始化为空。
  2. 遍历输入列表。对于每个输入元素:
    1. 找到结果列表中的所有元素,这些元素包含输入元素的 ID 或站点(或两者皆有)。
    2. 将它们合并(缩减)为一个结果列表成员。
    3. 同样添加输入元素。

使用经典循环,不使用流操作。

英文:

A simple approach:

  1. Create a result list and initialize it to empty.
  2. Iterate over the input list. For each input element:
    1. Find all elements in the result list that holds either an ID or a site (or both) from the input element.
    2. Combine (reduce) them into one result list member.
    3. Also add the input element.

Use a classical loop, no stream operation.

huangapple
  • 本文由 发表于 2020年9月25日 00:36:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64050717.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定