A simple approach is foreach in list1 and checks if an item is in list2 if not added to list3.
outer: for(String s : list1) { for(MyClass c : list2) if(c.getStr().equals(s)) continue outer; filteredList.add(c); }
If you find that you are still not confusing, extract the inner loop into the boolean function. You can also replace the classic foreach for the lambda stream iterator.
public static boolean isInList(ArrayList<MyClass> list, String s) { list2.stream().foreach((o)-> { if(o.getStr().equals(s)) { return true; } }); return false; } list1.stream().foreach((s) -> { if(!isInList(list2, s)) { list3.add(s); } });
but it really looks more unsightly / dirty and unnecessary for my eyes.
In addition, String str in your class does not have an open definition, so I used the getStr () method in both examples, assuming your class follows the java bean model and contains the getStr () method.
source share