我有一个String
数组和一个List<String>
。我想做的是使用具有较大大小的变量,并将其用作删除较小变量的值的基础。我还想获取另一个变量中不存在的较大变量的值。请注意,这两个变量在数据类型上不同的原因是String[] group
变量是 jsp 页中的复选框组,而List<String> existingGroup
是数据库中的 ResultSet。例如:
String[] group
包含:
Apple
Banana
Juice
Beef
List<String> existingGroup
包含:
Apple
Beef
Lasagna
Flower
Lychee
由于两个变量的大小不同,它仍然应该正确删除值。
到目前为止,我所拥有的是
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++) {
// ??
}
}
谢谢。
好的,我也会从将您的数组转换为List
开始。所以做
List<String> input = Arrays.asList(array);
//now you can do intersections
input.retainAll(existingGroup); //only common elements were left in input
或者,如果你想要不常见的元素,只需做
existingGroup.removeAll(input); //only elements which were not in input left
input.removeAll(existingGroup); //only elements which were not in existingGroup left
选择权在你:-(
List
接口提供的方法。
list.removeAll(Arrays.asList(array)); // Differences removed
或
list.retainAll(Arrays.asList(array)); // Same elements retained
根据您的需求。