比较和删除列表和数组java中不存在的元素

2024-05-09

我有一个String数组和一List<String>。我想要做的是使用较大尺寸的变量,并将其用作较小变量的值删除的基础。我还想获取另一个中不存在的较大变量的值。请注意,这两个变量的数据类型不同的原因是String[] group变量是来自 jsp 页面的复选框组,并且List<String> existingGroup是来自数据库的结果集。例如:

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++) {
            // ??
        }
    }

Thanks.


好的,我首先将您的数组转换为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

选择是你的:-)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

比较和删除列表和数组java中不存在的元素 的相关文章

随机推荐