I have two array lists e.g.
List a;
contains : 10/10/2014, 10/11/2016
List b;
contains : 10/10/2016
How can i do
If you only want find missing values in b, you can do:
List toReturn = new ArrayList(a);
toReturn.removeAll(b);
return toReturn;
If you want to find out values which are present in either list you can execute upper code twice. With changed lists.
You can use filter
in the Java 8 Stream
library
List<String> aList = List.of("l","e","t","'","s");
List<String> bList = List.of("g","o","e","s","t");
List<String> difference = aList.stream()
.filter(aObject -> {
return ! bList.contains(aObject);
})
.collect(Collectors.toList());
//more reduced: no curly braces, no return
List<String> difference2 = aList.stream()
.filter(aObject -> ! bList.contains(aObject))
.collect(Collectors.toList());
Result of System.out.println(difference);
:
[e, t, s]
You may call U.difference(lists)
method in underscore-java library. I am the maintainer of the project. Live example
import com.github.underscore.U;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(1, 2);
List<Integer> list3 = U.difference(list1, list2);
System.out.println(list3);
// [3]
}
}
List<String> l1 = new ArrayList<String>();
l1.add("apple");
l1.add("orange");
l1.add("banana");
l1.add("strawberry");
List<String> l2 = new ArrayList<String>();
l2.add("apple");
l2.add("orange");
System.out.println(l1);
System.out.println(l2);
for (String A: l2) {
if (l1.contains(A))
l1.remove(A);
}
System.out.println("output");
System.out.println(l1);
Output:
[apple, orange, banana, strawberry]
[apple, orange]
output
[banana, strawberry]
First convert list to sets.
// create an empty set
Set<T> set = new HashSet<>();
// Add each element of list into the set
for (T t : list)
set.add(t);
You can use Sets.difference(Set1, Set2)
, which returns extra items present in Set1.
You can use Sets.difference(Set2, Set1)
, which returns extra items present in Set2.
Here is a generic solution for this problem.
public <T> List<T> difference(List<T> first, List<T> second) {
List<T> toReturn = new ArrayList<>(first);
toReturn.removeAll(second);
return toReturn;
}