I want to iterate two lists and get new filtered list which will have values not present in second list. Can anyone help?
I have two lists - one is list of strings, and the other is list of MyClass
objects.
List<String> list1;
List<MyClass> list2;
MyClass {
MyClass(String val)
{
this.str = val;
}
String str;
...
...
}
I want filtered list of strings based on -> check second list for elements (abc) whose values not present in list1
.
List<String> list1 = Arrays.asList("abc", "xyz", "lmn");
List<MyClass> list2 = new ArrayList<MyClass>();
MyClass obj = new MyClass("abc");
list2.add(obj);
obj = new MyClass("xyz");
list2.add(obj);
Now I want new filtered list -> which will have value => "lmn". i.e. values not present in list2
whose elements are in list1
.
Overview However, we'll learn how to use the filter() method with as many condition filters as we require. More filters can be applied in a variety of methods, such using the filter() method twice or supplying another predicate to the Predicate. and() method.
You need to override equals() method in SchoolObj class. contains() method you will uses the equals() method to evaluate if two objects are the same. But better solution is to use Set for one list and filter in another list to collect if contains in Set. Set#contains takes O(1) which is faster.
Use negate() to write the reverse/negative conditions so that a single predicate may serve true and false – both scenarios. Use and() to combine two predicates for a logical AND operation. Use or() to combine two predicates for a logical OR operation.
// produce the filter set by streaming the items from list 2
// assume list2 has elements of type MyClass where getStr gets the
// string that might appear in list1
Set<String> unavailableItems = list2.stream()
.map(MyClass::getStr)
.collect(Collectors.toSet());
// stream the list and use the set to filter it
List<String> unavailable = list1.stream()
.filter(e -> unavailableItems.contains(e))
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With