如何从字符串数组创建词汇表

How to create vocabulary from Arrays of Strings

我必须用一些文本的独特词来制作一个词汇表。我将文本转换为字符串数组。现在我想要只有唯一单词的数组列表。所以第一步,将第一个字符串数组转换为 List<Strings>(我猜?),其中过滤掉所有双字。这是我的第一步,我该怎么做,我是使用 List<String> 还是另一个 String[]

其次,下一个 String[] I 'read-in' 应该更新词汇表 List<String> 但只从文本中添加新词。

它必须看起来像:

public List<String> makeVocabulary(String[] tokens){
     List<String> vocabulay = new ArrayList<>;
     //add unique words from 'tokens' to vocabulary
     return vocabulary;

}

TL;DR: 我如何将一大堆 String[] 转换为一个 List<String>,只有来自 String[]的?

查看您的代码后,您似乎每次 运行 此命令都会清除词汇,因此只能执行一次。如果您想使其更加模块化,请执行以下操作:

public class yourClass
{
    private List<String> vocabulary = new ArrayList<String>();

    public List<String> makeVocabulary(String[] tokens)
    {
        for( int i = 0; i < tokens.length; i++ )
            if( !vocabulary.contains( tokens[i] ) )
                vocabulary.add(tokens[i]);
        return vocabulary;
    }
}

要确定唯一标记,请使用 Set 实现...

public List<String> makeVocabulary(String[] tokens){
 Set<String> uniqueTokens = new HashSet<String>();
 for(String token : tokens) {
    uniqueTokens.add(token);
 }
 List<String> vocabulay = new ArrayList<String>(uniqueTokens);
 return vocabulary;

}

实现您的目标的一种方法是使用集合 class 而不是字符串列表。你可以调查那个,例如喜欢下面的代码。

public List<String> makeVocabulary(String[] tokens){
 Set<String> temp = new HashSet<>;
 //add unique words from 'tokens' to temp
 List<String> vocabulary = new ArrayList<>;
 vocabulary.addAll(temp);
 return vocabulary;
}

如果您可以接受 Set 作为 return 类型的 makeVocabulary,您可以 return temp.