Reputation: 921
Let consider two arraylists.
ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(2);
list1.add(3);
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2.add(3);
list2.add(4);
list2.add(5);
I want to perform AND and OR operation between these lists. For example, here when I perform AND operation b/w list1 & list2 output should be a list containing only 3 when I perform OR operation b/w list1 & list2 output should be a list containing 1,2,3,4,5(not 3 repeating twice).
Is there any possibility in Java to achieve this scenario? Can we use Java 8 Streams in this case? Please give me the most efficient way to get the answer.
Upvotes: 2
Views: 267
Reputation: 421170
Using the Stream API:
List<Integer> union = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());
List<Integer> intersection = list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());
Without the Stream API:
List<Integer> intersection = new ArrayList<>(list1);
intersection.retainAll(list2);
List<Integer> union = new ArrayList<>(list1);
List<Integer> toAdd = new ArrayList<>(list2);
toAdd.removeAll(list1); // avoid duplicates
union.addAll(toAdd);
Upvotes: 5
Reputation: 308
It could be useful:
Set<Integer> orSet = new HashSet<Integer>();
orSet.addAll(list);
orSet.addAll(list1);
List<Integer> orList = new ArrayList<Integer>(orSet);
List<Integer> andList = new ArrayList<Integer>();
int i=0;
Iterator<Integer> itr = list.iterator();
while(itr.hasNext()){
int v = itr.next();
if(list1.contains(v)){
andList.add(v);
}
}
System.out.println(orList);
System.out.println(andList);
Upvotes: 1
Reputation: 62874
If you really insist on Streams, here's what you can do:
For the AND, you can do:
List<Integer> AND = list1.stream()
.filter(list2:contains)
.collect(Collectors.toList());
For the OR, you can do:
List<Integer> OR = Arrays.asList(list1, list2)
.stream()
.flatMap(List::stream)
.distinct()
.collect(Collectors.toList());
or even better, as suggested by @Alexis C. and inspired by @aioobe:
List<Integer> OR = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());
Upvotes: 1
Reputation: 73568
You need to use Set
s to avoid duplicates. Then it's just a matter of using addAll()
, removeAll()
and retainAll()
operations.
Upvotes: 2