java – 在计算两个列表之间的重复值时如何短路?
发布时间:2020-12-15 08:25:55 所属栏目:Java 来源:网络整理
导读:我有2个列表,我需要以最快的方式计算/检查列表A中与列表B中的元素匹配的重复元素. 例如,如果列表A是[“A”,“B”,“C”],则列表B是[“X”,“A”,“C”,“ C“],我的计数器应该是2,因为B中有2个重复的元素(”B“和”C“).由于它是一个布尔方法,只要B中出现A的
我有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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |