0

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.

9
  • I am reading your input as id1 -> site1, site2, id2 -> site1, site2 and then : union id1 and id2. Is that correct? Commented Sep 24, 2020 at 16:58
  • 1
    but how do you know that id1 and id2 are to be joined because it is now : id1 -> site1, site2, id2 -> site1, site2, the ids has to be in the other row for them to be joined. if they are separated as 1 id per row , join is not possible correct Commented Sep 24, 2020 at 17:02
  • The relation between ids and sites is many to one.. sorry I updated my input data in the question. Commented Sep 24, 2020 at 17:08
  • 1
    They rather seem to be many-to-many. I haven’t thought it through, but my immediate idea is that streams are poorly suited for this. Commented Sep 24, 2020 at 18:23
  • 1
    @Coder123 , sorry, I meant Union-Find. Commented Sep 24, 2020 at 18:37

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.