Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterating and filtering two lists using java 8

Tags:

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.

like image 681
Arun Khot Avatar asked Apr 07 '15 11:04

Arun Khot


People also ask

Can we use multiple filters in Java 8?

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.

How do I compare two lists in java8?

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.

How do you add two conditions to a stream filter?

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.


1 Answers

// 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());
like image 155
Ashley Frieze Avatar answered Sep 19 '22 21:09

Ashley Frieze