I have two arrayLists with 3 integer. I want to find a way to return the common elements of the two lists. Has anynody idea, how can I achieve this?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
listA.retainAll(listB); // listA now contains only the elements which are also contained in listB.
If you want to avoid that changes are being affected in listA
, then you need to create a new one.
List common = new ArrayList(listA); common.retainAll(listB); // common now contains only the elements which are contained in listA and listB.
回答2:
You can use set intersection operations with your ArrayList
objects.
Something like this:
List l1 = new ArrayList(); l1.add(1); l1.add(2); l1.add(3); List l2= new ArrayList(); l2.add(4); l2.add(2); l2.add(3); System.out.println("l1 == "+l1); System.out.println("l2 == "+l2); List l3 = new ArrayList(l2); l3.retainAll(l1); System.out.println("l3 == "+l3); System.out.println("l2 == "+l2);
Now, l3
should have only common elements between l1
and l2
.
CONSOLE OUTPUT l1 == [1, 2, 3] l2 == [4, 2, 3] l3 == [2, 3] l2 == [4, 2, 3]
回答3:
Why reinvent the wheel? Use Commons Collections:
CollectionUtils.intersection(java.util.Collection a, java.util.Collection b)
回答4:
Using Java 8's Stream.filter()
method in combination with List.contains()
:
import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; /* ... */ List list1 = asList(1, 2, 3, 4, 5); List list2 = asList(1, 3, 5, 7, 9); List common = list1.stream().filter(list2::contains).collect(toList());
回答5:
List lista =new ArrayList(); List listb =new ArrayList(); lista.add("Isabella"); lista.add("Angelina"); lista.add("Pille"); lista.add("Hazem"); listb.add("Isabella"); listb.add("Angelina"); listb.add("Bianca"); // Create an aplusb list which will contain both list (list1 and list2) in which common element will occur twice List listapluslistb =new ArrayList(lista); listapluslistb.addAll(listb); // Create an aunionb set which will contain both list (list1 and list2) in which common element will occur once Set listaunionlistb =new HashSet(lista); listaunionlistb.addAll(listb); for(String s:listaunionlistb) { listapluslistb.remove(s); } System.out.println(listapluslistb);
回答6:
In case you want to do it yourself..
List commons = new ArrayList(); for (Integer igr : group1) { if (group2.contains(igr)) { commons.add(igr); } } System.out.println("Common elements are :: -"); for (Integer igr : commons) { System.out.println(" "+igr); }
回答7:
// Create two collections: LinkedList listA = new LinkedList(); ArrayList listB = new ArrayList(); // Add some elements to listA: listA.add("A"); listA.add("B"); listA.add("C"); listA.add("D"); // Add some elements to listB: listB.add("A"); listB.add("B"); listB.add("C"); // use List common = new ArrayList(listA); // use common.retainAll common.retainAll(listB); System.out.println("The common collection is : " + common);