我想删除数组中的所有重复项,然后将结果写入空数组

时间:2015-04-29 17:35:05

标签: java arrays jsp

我想删除数组中的所有重复项,然后将结果写入空数组。

这是我到目前为止所拥有的......

String arIndex[] = new String[rows];    
String value[]; //This is my empty array


for(int i = 0; i < rows; i++) {
    if (Arrays.asList(value).contains(arIndex)) {
        out.println("Already Exist!");
    } else {
        asList[i] = value[i];
    }
}

有人可以告诉我如何实现这个目标吗?

感谢

1 个答案:

答案 0 :(得分:2)

由于您正在处理Strings,只要您的结果不必考虑区分大小写,您就可以使用HashMap来计算您的出现次数。然后,当填充HashMap时,您可以遍历它并将值为1(不重复)的所有实例移动到数组(某种类型的List)。

你会在我的代码示例中看到每个字符串都成为我的HashMap中的一个键,键的计数就是值。我不关心套管,这就是为什么在结果中你会看到Hello和hello不被认为是重复的。如果您想考虑重复,那么您可以修改我的示例代码以忽略大小写。

public static void main(String[] args) throws Exception {
    String[] arIndex = new String[] {"the", "the", "1", "2", "Hello", "hello", "2"};
    Map<String, Integer> occurrences = new HashMap<>();

    // Count occurences of each string in the array
    for (int i = 0; i < arIndex.length; i++) {
        if (occurrences.containsKey(arIndex[i])) {
            occurrences.put(arIndex[i], occurrences.get(arIndex[i]) + 1);
        } else {
            occurrences.put(arIndex[i], 1);
        }
    }

    List<String> nonDuplicatesList = new ArrayList<>();
    for (Map.Entry<String, Integer> occurrence : occurrences.entrySet()) {
        if (occurrence.getValue() == 1) {
            nonDuplicatesList.add(occurrence.getKey());
        }
    }

    // Only do this if you're bounded to an array, otherwise just use the nonDuplicatesList
    Object[] value = nonDuplicatesList.toArray();
    System.out.println(Arrays.toString(value));
}

结果:

enter image description here

更新

看到你的评论后,一个值为[1,1,2,3]的数组应该会产生[1,2,3],下面的代码更改就是你的意思。

public static void main(String[] args) throws Exception {
    String[] arIndex = new String[] {"the", "the", "1", "2", "Hello", "hello", "2"};
    Map<String, Integer> occurrences = new HashMap<>();

    for (int i = 0; i < arIndex.length; i++) {
        if (occurrences.containsKey(arIndex[i])) {
            // Ignore this value cause it's a duplicate
            continue;
        } else {
            occurrences.put(arIndex[i], 1);
        }
    }

    arIndex = new String[occurrences.size()];
    occurrences.keySet().toArray(arIndex);

    System.out.println(Arrays.toString(arIndex));
}

结果:

enter image description here

更新

只有ArrayList

的另一种方式
public static void main(String[] args) throws Exception {
    String[] arIndex = new String[] {"the", "the", "1", "2", "Hello", "hello", "2"};

    List<String> removedDuplicates = new ArrayList<>();
    for (String arIndex1 : arIndex) {
        if(!removedDuplicates.contains(arIndex1)) {
            removedDuplicates.add(arIndex1);
        }
    }

    // Setting the removedDuplicates to arIndex
    arIndex = new String[removedDuplicates.size()];
    removedDuplicates.toArray(arIndex);
    System.out.println(Arrays.toString(arIndex));
}

结果:

enter image description here