简体   繁体   English

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

[英]I want to remove all duplicates in an array and then write the results to an empty array

I want to remove all duplicates in an array and then write the results to an empty array. 我想删除数组中的所有重复项,然后将结果写入空数组。

Here is what I have so far... 这是我到目前为止所拥有的......

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];
    }
}

Could someone give me an idea on how to accomplish this? 有人能告诉我如何实现这个目标吗?


Thanks 谢谢

Arrays are statically allowed, with a fixed size. 静态允许数组,具有固定大小。 Collections are more appropriate in java, and available in the java.util package. 集合在java中更合适,并且可以在java.util包中找到。 You'll find the most common data structures, such as lists, queues, sets, maps etc. 您将找到最常见的数据结构,例如列表,队列,集,地图等。

In your specific case, you should use Set , which inherently removes duplicates . 在您的特定情况下,您应该使用Set ,它本身会删除重复项 So you would just add everything to it with the add() method, and duplicates would be automatically ignored: 因此,您只需使用add()方法向其添加所有内容,并且将自动忽略重复项:

String arIndex[] = new String[rows];
// arIndex is probably filled with something useful here

Set<String> output = new HashSet<>(); // this set will hold your non-duplicated elements

for (String s : arIndex) { 
    output.add(s); // add() ignores the element if already present
}

// now output contains all your values only once:
for (String s : output) { 
    System.out.println(s); 
}

Then, if you really need the output as an array (which you actually should not need), you can use the following after the loop: 然后,如果您确实需要输出作为数组(实际上您不需要),则可以在循环后使用以下内容:

String[] outputArray = output.toArray(new String[output.size()]);

Since you're dealing with Strings , as long as your result doesn't have to account for case sensitive, you can use a HashMap to count your occurrences. 由于您正在处理Strings ,只要您的结果不必考虑区分大小写,您就可以使用HashMap来计算出现次数。 Then when your HashMap is populated, you can iterate through it and move all occurrences whose value is 1 (Not duplicated) to an array (List of some sort). 然后,当填充HashMap时,您可以遍历它并将值为1(不重复)的所有实例移动到数组(某种类型的List)。

You'll see in my code sample that each string becomes a key in my HashMap and the count of the key is the value. 您将在我的代码示例中看到每个字符串都成为我的HashMap中的一个键,键的计数就是值。 I don't care about casing which is why in the results you'll see that Hello and hello are not considered duplicated. 我不关心套管,这就是为什么在结果中你会看到Hello和hello不被认为是重复的。 If you want to consider that duplicated then you can modified my sample code to ignore case. 如果您想考虑重复,那么您可以修改我的示例代码以忽略大小写。

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));
}

Results: 结果:

在此输入图像描述

Update 更新

After seeing your comment, that an array with values [1, 1, 2, 3] should result in [1, 2, 3], the following code change get's you that. 看到你的评论后,一个值为[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));
}

Results: 结果:

在此输入图像描述

Update 更新

Another way with just an ArrayList 另一种只有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));
}

Results: 结果:

在此输入图像描述

Suggestion for beginners - try not to bring your experience but enjoy Java. 对初学者的建议 - 尽量不要带来你的经验,但享受Java。 Don't use arrays - use Collections. 不要使用数组 - 使用集合。 Don't check what is already checked - duplication in particular. 不要检查已检查的内容 - 特别是重复。 Then your code will look like Java code: 然后你的代码看起来像Java代码:

TreeSet<String> set=new TreeSet<String>(); // TreeSet has no duplication
set.add(value); //  add something
set.addAll(anotherSet); // better choice

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

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