简体   繁体   English

使用Java8匹配方法比较两个列表

[英]Comparing two list by using Java8 Matching Methods

Using Java8 matching methods am able to compare two list and getting the boolean results when if the is any match is available in both the lists. 使用Java8匹配方法能够比较两个列表,并且如果两个列表中都存在,则可以获取布尔结果。

Please find my below code for that. 请找到我下面的代码。

public class StreamTest2 {

    public static void main(String args[]) {

        List<Integer> aList = Arrays.asList( new Integer[] {
                1,3,5,6,8
        });

        List<Integer> bList = Arrays.asList( new Integer[] {
                10, 89, 8, 9
        });

        //If any number in List1 present in List2
        System.out.println("If any number present in aList is present in bList : "+aList.stream().anyMatch(num -> bList.contains(num)));

    }

}

Output : 输出:

If any number present in aList is present in bList : true

But, i want to print the matching number from both the list, how i can print the matching number ? 但是,我想从两个列表中打印匹配号码,我如何打印匹配号码?

You can use filter and findFirst : 您可以使用filterfindFirst

System.out.println("If any number present in aList is present in bList : "+aList.stream().filter(num -> bList.contains(num)).findFirst().orElse(null));

This will print the matching number if found (it will stop at the first match), or null , if no match is found. 如果找到匹配项,它将打印匹配号(它将在第一个匹配项处停止);如果找不到匹配项,则将打印null

Or, you can collect all the matches into a List : 或者,您可以将所有匹配项收集到一个List

System.out.println("If any number present in aList is present in bList : "+aList.stream().filter(num -> bList.contains(num)).collect(Collectors.toList());

试试这个

aList.stream().filter(bList::contains).collect(Collectors.toSet());

The reason because of which you get java.lang.UnsupportedOperationException when you call retainAll is that Arrays#asList returns an ArrayList backed by an array of fixed size. 因为其中的你的理由java.lang.UnsupportedOperationException当你调用retainAllArrays#asList返回由固定大小的数组支持的一个ArrayList。 Any attempt to remove or add an element to these lists will result in the aforementioned UnsupportedOperationException . 任何尝试将元素删除或添加到这些列表的操作都将导致上述UnsupportedOperationException

The solution is, as @LuCio has suggested, to wrap the Arrays.asList part with a ArraysList constructor call, as such: 如@LuCio所建议的,解决方案是使用ArraysList构造函数调用包装Arrays.asList部分,如下所示:

List<Integer> aList = new ArrayList(Arrays.asList(1,3,5,6,8));
List<Integer> bList = new ArrayList(Arrays.asList(10, 89, 8, 9));

the you should be able to call: 您应该可以致电:

aList.retainAll(bList);

Keep in mind that this will modify the original aList list. 请记住,这将修改原始的aList列表。 If you need to preserve the state of aList then I would suggest to make a copy of aList before invoking retainAll . 如果您需要保留的状态aList那么我会建议做的副本aList调用之前retainAll One of the suggested Stream API approached would in this case maybe be more suitable. 在这种情况下,建议的Stream API之一可能会更适合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM