简体   繁体   中英

Reduce elements in a java list using Java8 streams

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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