2

我有一个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++) {
            // ??
        }
    }

谢谢。

4

2 回答 2

4

好的,我将从将您的数组转换为该数组开始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

选择是你的:-)

于 2013-10-09T11:00:30.677 回答
3

您可以使用List接口提供的方法。

list.removeAll(Arrays.asList(array)); // Differences removed

或者

list.retainAll(Arrays.asList(array)); // Same elements retained

根据您的需求。

于 2013-10-09T10:59:27.827 回答