1

I have three lists of strings. Now I need to make sure that an element is present in only one of those three list. I don't want to have duplicates across the lists. You can assume that there are no duplicates within each list.

I tried to use the removeIf() and its serving my purpose. Im sure that is not the best way to do it. Is there any other way to do it in Java 8+?

The Priority for the lists is list1 > list2 > list3

List<String> list1 = Stream.of("23","45","655","43","199").collect(Collectors.toList());
List<String> list2 = Stream.of("13","23","54","655","111","13").collect(Collectors.toList());
List<String> list3 = Stream.of("76","45","33","67","43","13").collect(Collectors.toList());

list2.removeIf(i->list1.contains(i));
list3.removeIf(i->list1.contains(i) || list2.contains(i));

System.out.println(list1);
System.out.println(list2);
System.out.println(list3);

The output is below which is expected

[23, 45, 655, 43, 199]
[13, 54, 111, 13]
[76, 33, 67]
1
  • list2.removeAll(list1); for the first step would be neat. Also, if you have used Set instead of a list, the complexity would have been O(n) for each step. for lists it is O(n^2) Commented May 14, 2021 at 11:11

1 Answer 1

7

I will recommend to use Set instead of List since Set is of O(1) time complexity

 List<String> list1 = Stream.of("23","45","655","43","199").collect(Collectors.toList());
 List<String> list2 = Stream.of("13","23","54","655","111","13").collect(Collectors.toList());
 List<String> list3 = Stream.of("76","45","33","67","43","13").collect(Collectors.toList());

And then just stream all there by combining and just collect distinct elements into corresponding lists using Collectors.groupingBy

Collection<List<String>> result = Stream.of(list1,list2,list3)
            .flatMap(List::stream)
            .distinct()
            .collect(Collectors.groupingBy(v->list1.contains(v) ? 0 : (list2.contains(v) ? 1 : 2))).values();

    System.out.println(result);  //[[23, 45, 655, 43, 199], [13, 54, 111], [76, 33, 67]]
Sign up to request clarification or add additional context in comments.

1 Comment

Quite complicated, but you did it one line.

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.