Java – how to short circuit when calculating duplicate values between two lists?
•
Java
I have 2 lists. I need to calculate / check the duplicate elements in list a that match the elements in List B in the fastest way
For example, if list a is ["a", "B", "C"], then list B is ["X", "a", "C", "C"], my counter should be 2, because there are two duplicate elements ("B" and "C") in B. since it is a boolean method, it should return true whenever there is any repetition of a in B
I'm avoiding cascading loops and even trying to use streams Although the following code works, I'm still not sure about its design That's how I do it now:
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;
}
Solution
This will help you Let me know if you have any questions You can also use parallel streams if necessary
Using the 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;
}
No 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;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
