1

im currently working on a code to group Arrays based on their Elements and i hope u can help me out with your wisdom.

I have given following Arrays:

List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C", "F", "I"));
List<String> list2 = new ArrayList<String>(Arrays.asList("B", "C", "D", "E", "F"));
List<String> list3 = new ArrayList<String>(Arrays.asList("J", "K", "B", "L", "F"));
List<String> list4 = new ArrayList<String>(Arrays.asList("L", "K", "D", "C", "J"));

Now i want to compare which of these lists have 3 Elements in common and save that ListNames in a new List/Array.

commonList1{List2, List3,}       - (B,C,F)
commonList4{List5}               - (K,J,L)

Has anyone a smarter idea for doing that, instead of running through all Lists, compare each with another and search how many lists have the same intersection?

Best wishes Tom

Thom4Zz
  • 27
  • 2
  • 3
    Best off using a `set` – achAmháin Nov 15 '17 at 16:01
  • At least the naive `Set` implementation would be faster. Therefore collect each into its own set, then compute the set intersections like you would do it with arrays. The advantage, `Set` can answer `contains` in `O(1)` (fast) (at least on the average). – Zabuzard Nov 15 '17 at 16:03
  • IMHO duplicate of this: https://stackoverflow.com/a/36110216/1828296 – lospejos Nov 15 '17 at 16:04
  • @lospejos I already looked at that thread, the problem is, that if im doing in in that ways, I only get the common elements of all Lists. But I would like to group the lists, where atleast 3 elements are in common. Soryy if my question was unclear in that point – Thom4Zz Nov 15 '17 at 16:16
  • The problem is not well-defined unless you specify which intersection set you are interested in. Lists `a` and `b` could have a common intersection of 3 elements, and lists `b` and `c` could have an intersection set of 3 different elements. – Jim Garrison Nov 15 '17 at 16:27
  • Correct, I edited it therefore. – Thom4Zz Nov 15 '17 at 16:38
  • 1
    `list1.retainAll(list2); // listA now contains only the elements which are also contained in listB.` – Procrastinator Nov 15 '17 at 16:38

1 Answers1

1
listA.retainAll(listB);

listA holds the elements which are also contained in listB. To avoid changing listA, then you need to create a new list.

List<Integer> common = new ArrayList<Integer>(listA);
common.retainAll(listB);

The code above allows you to keep from changing listA or listB and common now contains only the elements which are contained in listA and listB.

Ash_s94
  • 787
  • 6
  • 19
  • You just copied and pasted answer from [here](https://stackoverflow.com/questions/5943330/common-elements-in-two-lists#answer-5943349). Also, you didn't copy the information properly with links. Please make it comment or link the OP to proper documentations. – Procrastinator Nov 16 '17 at 08:07