Arun Khot Arun Khot - 2 months ago 5
Java Question

iterating and filtering two lists using java 8

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
.

Answer

Finally I got way to achieve this following way -

List<String> unavailable = list1.stream()
                .filter(e -> (list2.stream()
                        .filter(d -> d.getStr().equals(e))
                        .count())<1)
                        .collect(Collectors.toList());

But this is also working as expected. Please let me know how much this is effective? and if anyone has other way to do same thing?

Comments