删除数组中的重复项Java

时间:2014-03-18 03:11:29

标签: java arrays string counter

我编写了一种计算单词文件中单词出现次数的方法。之前,在另一种方法中,我已将单词排序为按字母顺序显示。这个方法的示例输入如下所示: 是 远 鸟类 鸟类 去 去 具有

我的问题是..如何删除此方法中重复出现的内容? (在计算ofcoz之后)我试图使用另一个字符串数组将唯一的数组复制到该字符串数组中,但我得到一个空指针异常。

public static String[] counter(String[] wordList)
{
    for (int i = 0; i < wordList.length; i++) 
    {
         int count = 1;
         for(int j = 0; j < wordList.length; j++)
         {
             if(i != j)  //to avoid comparing itself
             {
                 if (wordList[i].compareTo(wordList[j]) == 0)   
                 {
                     count++;
                 }
             }
         }

         System.out.println (wordList[i] + " " + count);


     }

    return wordList; 
}

任何帮助将不胜感激。

哦,我目前的输出看起来像这样: 是1 离开1 鸟类2 鸟类2 去2 去2 有1个

2 个答案:

答案 0 :(得分:1)

我更喜欢使用Map存储单词出现次数。地图中的键存储在Set中,因此无法复制。这样的事情怎么样?

public static String[] counter(String[] wordList) {
    Map<String, Integer> map = new HashMap<>();

    for (int i = 0; i < wordList.length; i++) {
        String word = wordList[i];

        if (map.keySet().contains(word)) {
            map.put(word, map.get(word) + 1);
        } else {
            map.put(word, 1);
        }
    }

    for (String word : map.keySet()) {
        System.out.println(word + " " + map.get(word));
    }

    return wordList;
}

答案 1 :(得分:0)

我已在this question上发布了答案。你的问题几乎完全相同 - 他在创建另一个阵列和获得NPE时遇到了问题。

这就是我提出的(假设数组已排序):

public static String[] noDups(String[] myArray) { 

    int dups = 0; // represents number of duplicate numbers

    for (int i = 1; i < myArray.length; i++) 
    {
        // if number in array after current number in array is the same
        if (myArray[i].equals(myArray[i - 1]))
            dups++; // add one to number of duplicates
    }

    // create return array (with no duplicates) 
    // and subtract the number of duplicates from the original size (no NPEs)
    String[] returnArray = new String[myArray.length - dups];

    returnArray[0] = myArray[0]; // set the first positions equal to each other
                                 // because it's not iterated over in the loop

    int count = 1; // element count for the return array

    for (int i = 1; i < myArray.length; i++)
    {
        // if current number in original array is not the same as the one before
        if (!myArray[i].equals(myArray[i-1])) 
        {
           returnArray[count] = myArray[i]; // add the number to the return array
           count++; // continue to next element in the return array
        }
    }

    return returnArray; // return the ordered, unique array
}

示例输入/输出:

String[] array = {"are", "away", "birds", "birds", "going", "going", "has"};

array = noDups(array);

// print the array out
for (String s : array) {
    System.out.println(s);
}

输出:

are
away
birds
going
has