繁体   English   中英

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

[英]Comparing and removing elements not present in a List and array java

我有一个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

根据您的需求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM