Intersection and Union of Arraylists in Java

Intersection and union of ArrayLists in Java

Here's a plain implementation without using any third-party library. Main advantage over retainAll, removeAll and addAll is that these methods don't modify the original lists input to the methods.

public class Test {

public static void main(String... args) throws Exception {

List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C"));
List<String> list2 = new ArrayList<String>(Arrays.asList("B", "C", "D", "E", "F"));

System.out.println(new Test().intersection(list1, list2));
System.out.println(new Test().union(list1, list2));
}

public <T> List<T> union(List<T> list1, List<T> list2) {
Set<T> set = new HashSet<T>();

set.addAll(list1);
set.addAll(list2);

return new ArrayList<T>(set);
}

public <T> List<T> intersection(List<T> list1, List<T> list2) {
List<T> list = new ArrayList<T>();

for (T t : list1) {
if(list2.contains(t)) {
list.add(t);
}
}

return list;
}
}

How to do union, intersect, difference and reverse data in java

//Union 
List<Integer> c = new ArrayList<Integer>(a.size() + b.size());
addNoDups(c,a);
addNoDups(c,b);

private void addNoDups(List<Integer> toAddTo,List<Integer> iterateOver) {
for(Integer num:iterateOver){
if(toAddTo.indexOf(num) == -1) {
toAddTo.add(num);
}
}
}

//intersection
List<Integer> c = new ArrayList<Integer> (a.size() > b.size() ?a.size():b.size());
c.addAll(a);
c.retainAll(b);

//difference a-b
List<Integer> c = new ArrayList<Integer> (a.size());
c.addAll(a);
c.removeAll(b);

element intersection between multiple arrayList

If you want to compute intersections, you should almost certainly be using a Set rather than a List. Sets are great for handling unordered collections and operations like union and intersection (with removeAll and retainAll). They are also more efficient for answering questions like "is this element contained in the collection?"

Hope this helps!

List difference in java

List<Integer> original = Arrays.asList(12,16,17,19,101);
List<Integer> selected = Arrays.asList(16,19,107,108,109);

ArrayList<Integer> add = new ArrayList<Integer>(selected);
add.removeAll(original);
System.out.println("Add: " + add);

ArrayList<Integer> remove = new ArrayList<Integer>(original);
remove.removeAll(selected);
System.out.println("Remove: " + remove);

Output:

Add: [107, 108, 109]
Remove: [12, 17, 101]

Uses Collection's removeAll method. See javadocs.

Intersect and union of two different list of custom objects with streams

This should do it, but in the example there are 5 records in each list that have same ids.

List<OutputData> result = listOfData1.stream()
.flatMap(x -> listOfData2.stream()
.filter(y -> x.getId() == y.getId())
.map(y -> new OutputData(y.getId(), x.getName(), y.getType(), x.getAmount())))
.collect(Collectors.toList());


Related Topics



Leave a reply



Submit