Reputation: 853
I have one String
array and one List<String>
. What I want to do is to use the variable with a larger size and use that as the basis of the values removal of the smaller variable. I also want to get the values of the larger sized variable not present in the other. Note that the reason why the two variables differ on datatype is because the String[] group
variable is a checkbox group from a jsp page and the List<String> existingGroup
is a ResultSet from the database. For example:
String[] group
contains:
Apple
Banana
Juice
Beef
List<String> existingGroup
contains:
Apple
Beef
Lasagna
Flower
Lychee
And since the size of the two variables vary, it should still correctly remove the values.
What I have so far is
if(groupId.length >= existingGroup.size()) {
for(int i = 0; i < groupId.length; i++) {
if(! existingGroup.contains(groupId[i])) {
if(existingGroup.get(existingGroup.indexOf(groupId[i])) != null) {
// I'm unsure if I'm doing this right
}
}
}
} else {
for(int i = 0; i < existingGroup.size(); i++) {
// ??
}
}
Thanks.
Upvotes: 2
Views: 4197
Reputation: 45060
You can use the methods the List
interface provides.
list.removeAll(Arrays.asList(array)); // Differences removed
or
list.retainAll(Arrays.asList(array)); // Same elements retained
based on your needs.
Upvotes: 3
Reputation: 27496
Ok, I would start with converting your array into the List
too. So do
List<String> input = Arrays.asList(array);
//now you can do intersections
input.retainAll(existingGroup); //only common elements were left in input
Or, if you want elements which are not common, just do
existingGroup.removeAll(input); //only elements which were not in input left
input.removeAll(existingGroup); //only elements which were not in existingGroup left
Choice is yours:-)
Upvotes: 4