微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 在计算两个列表之间的重复值时如何短路?

我有2个列表,我需要以最快的方式计算/检查列表A中与列表B中的元素匹配的重复元素.

例如,如果列表A是[“A”,“B”,“C”],则列表B是[“X”,“A”,“C”,“ C“],我的计数器应该是2,因为B中有2个重复的元素(”B“和”C“).由于它是一个布尔方法,只要B中出现A的任何重复,它就应该返回true.

我正在避免级联循环甚至尝试使用流.虽然以下代码有效,但我对它的设计仍然不太确定.
这就是我现在这样做的方式:

class MyPojo {
    int value; String str;
    MyPojo(int value) { this.value = value; };
    /* getters & setters*/ 
}

public static boolean hasDuplicates() {
    List<Integer> forbiddenValues = Arrays.asList(1,2,3);
    List<MyPojo> pojoList = Arrays.asList(new MyPojo(0),new MyPojo(2),new MyPojo(3),new MyPojo(4));

    for ( Integer value : forbiddenValues) {
        long count = pojoList.stream()
            .filter( pojoElement -> pojoElement.getValue() == value)
            .count();
        // returns true if in a single iteration count is greater than 1
        if ( count > 1) {
           return true;
        }
    }
    return false;
}

解决方法

这对你有用.让我知道你有任何问题.如果需要,您也可以使用并行流.

使用Stream API

public static boolean hasDuplicates() {
        List<Integer> forbiddenValues = Arrays.asList(1,3);

        List<MyPojo> pojoList = Arrays.asList(new MyPojo(0),new MyPojo(4));


        long count = pojoList.stream()
                .filter(pojo -> forbiddenValues.contains(pojo.getValue()))
                .map(MyPojo::getValue)
                .collect(Collectors.groupingBy(value -> value))
                .values()
                .stream()
                .filter(values -> values.size() > 1)
                .count();

        return count > 1;
    }

没有Streams

public static boolean hasDuplicates() {
        List<Integer> forbiddenValues = Arrays.asList(1,new MyPojo(4));


        Map<Integer,Integer> counts = new HashMap<>();

        for(int forbidden : forbiddenValues){
            counts.put(forbidden,0);
        }

        for(MyPojo myPojo : pojoList){
            if(counts.containsKey(myPojo.getValue())){
                int count = counts.get(myPojo.getValue());

                if(count == 1){
                    return true;
                }

                counts.put(myPojo.getValue(),count + 1);
            }
        }

        return false;
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐