iterating and filtering two lists using java 8

后端 未结 9 519
抹茶落季
抹茶落季 2020-12-09 17:21

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,

9条回答
  •  醉话见心
    2020-12-09 17:49

    If you stream the first list and use a filter based on contains within the second...

    list1.stream()
        .filter(item -> !list2.contains(item))
    

    The next question is what code you'll add to the end of this streaming operation to further process the results... over to you.

    Also, list.contains is quite slow, so you would be better with sets.

    But then if you're using sets, you might find some easier operations to handle this, like removeAll

    Set list1 = ...;
    Set list2 = ...;
    Set target = new Set();
    target.addAll(list1);
    target.removeAll(list2);
    

    Given we don't know how you're going to use this, it's not really possible to advise which approach to take.

提交回复
热议问题