如何计算ArrayList中的唯一值?

7 java string unique arraylist

我必须使用Java计算文本文档中唯一单词的数量.首先,我必须摆脱所有单词中的标点符号.我使用Scanner该类扫描文档中的每个单词并放入一个字符串ArrayList.

所以,下一步是我遇到问题的地方!如何创建一个可以计算数组中唯一字符串数的方法?

例如,如果数组包含apple,bob,apple,jim,bob; 此数组中唯一值的数量为3.


public countWords() {
    try {
        Scanner scan = new Scanner(in);
        while (scan.hasNext()) {
            String words = scan.next();
            if (words.contains(".")) {
                words.replace(".", "");
            }
            if (words.contains("!")) {
                words.replace("!", "");
            }
            if (words.contains(":")) {
                words.replace(":", "");
            }
            if (words.contains(",")) {
                words.replace(",", "");
            }
            if (words.contains("'")) {
                words.replace("?", "");
            }
            if (words.contains("-")) {
                words.replace("-", "");
            }
            if (words.contains("‘")) {
                words.replace("‘", "");
            }
            wordStore.add(words.toLowerCase());
        }
    } catch (FileNotFoundException e) {
        System.out.println("File Not Found");
    }
    System.out.println("The total number of words is: " + wordStore.size());
}
Run Code Online (Sandbox Code Playgroud)

kos*_*osa 20

你被允许使用Set吗?如果是这样,你HashSet可以解决你的问题.HashSet不接受重复.

HashSet noDupSet = new HashSet();
noDupSet.add(yourString);
noDupSet.size();
Run Code Online (Sandbox Code Playgroud)

size() method返回唯一字的数量.

如果你必须真正使用ArrayList,那么一种方法可能是,

1) Create a temp ArrayList
2) Iterate original list and retrieve element
3) If tempArrayList doesn't contain element, add element to tempArrayList
Run Code Online (Sandbox Code Playgroud)


ROM*_*eer 13

Java 8开始,您可以使用Stream:

在以下内容中添加元素后ArrayList:

long n = wordStore.stream().distinct().count();
Run Code Online (Sandbox Code Playgroud)

它将您转换ArrayList为流,然后它只计算不同的元素.