简体   繁体   English

使用 Java8 流减少 Java 列表中的元素

[英]Reduce elements in a java list using Java8 streams

I have a java list that contains elements like below:我有一个包含如下元素的 java 列表:

Input List name is itemsList:输入列表名称是 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.我知道这不是一个容易解决的问题。

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.在结果列表中查找包含输入元素中的 ID 或站点(或两者)的所有元素。
    2. Combine (reduce) them into one result list member.将它们合并(减少)为一个结果列表成员。
    3. Also add the input element.还要添加输入元素。

Use a classical loop, no stream operation.使用经典循环,无流操作。

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

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