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;
    }

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...