【问题标题】:Comparing and removing elements not present in a List and array java比较和删除列表和数组java中不存在的元素
【发布时间】:2013-10-16 16:46:34
【问题描述】:

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

谢谢。

【问题讨论】:

标签: java arrays list


【解决方案1】:

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

选择权在你手中:-)

【讨论】:

  • 这很好,但我也需要它们之间的差异,而不仅仅是共同的元素。我认为我在帖子开头的陈述含糊不清,所以我重新措辞。
  • retainAll 抱怨变量必须是boolean 类型。这是获取公共元素的正确方法吗?
【解决方案2】:

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

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

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

根据您的需要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-22
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-17
    • 2014-02-13
    • 1970-01-01
    相关资源
    最近更新 更多