Reputation: 1272
Hi i am taking common count in two list.
Here is my code.
public static int getMatchCount(List<String> listOne, List<String> listTwo) {
String valueOne = "";
String valueTwo = "";
int matchCount = 0;
boolean isMatchedOnce=false;
for (int i = 0; i < listOne.size(); i++) {
valueOne = listOne.get(i);
isMatchedOnce=false;
if (StringUtils.isBlank(valueOne))
continue;
for (int j = 0; j < listTwo.size(); j++) {
valueTwo = listTwo.get(j);
if (StringUtils.isBlank(valueTwo))
continue;
if (valueTwo.equals(valueOne) && (!isMatchedOnce)) {
matchCount++;
listOne.set(i, "");
listTwo.set(j, "");
isMatchedOnce=true;
}
}
}
return matchCount;
}
for ex
listone listTwo
A A
A B
B
Then result is 2 not 3
As their is only two common pair we can take out.
But the method is very slow Any Improvement in Above method to make it quick.
Upvotes: 0
Views: 800
Reputation: 17839
maybe you can try this ...
public static int getMatchCount(List<String> listOne, List<String> listTwo) {
String valueOne;
String valueTwo;
int matchCount = 0;
boolean isMatchedOnce;
//for (int i = 0; i < listOne.size(); i++) {
for(String i : listOne){
valueOne = i;
isMatchedOnce = false;
if (StringUtils.isBlank(valueOne)) {
continue;
}
for (String j : listTwo) {
valueTwo = j;
if (StringUtils.isBlank(valueTwo)) {
continue;
}
if (valueTwo.equals(valueOne) && (!isMatchedOnce)) {
matchCount++;
listOne.set(listOne.indexOf(i), "");
listTwo.set(listOne.indexOf(j), "");
isMatchedOnce = true;
}
}
}
return matchCount;
}
Upvotes: 0
Reputation: 15052
This should be an easier work around:
List<String> listOne = new ArrayList<String>();
//add elements
List<String> listTwo= new ArrayList<String>();
//add elements
List<String> commonList = new ArrayList<String>(listTwo);
commonList.retainAll(listOne);
int commonListSize = commonList.size();
Upvotes: 4
Reputation: 298838
Use an interim Collection and addAll(), retainAll():
Set<String> set = new HashSet<String>();
set.addAll(list1);
set.retainAll(list2);
int count = set.size();
Upvotes: 2