java - 尝试从枚举类创建字符串的 ArrayList

标签 java arraylist enums simplify

我已经能够从枚举类的值成功加载我的ArrayList。我对使用枚举不太熟悉,我想知道是否有一种方法可以处理这个问题,而无需像我所展示的那样为每个枚举键入 add 。

public enum PartsOfSpeech {
    Adjective("Placeholder [adjective] : To be updated..."),
    Adverb("Placeholder [adverb] : To be updated..."),
    Conjunction("Placeholder [conjection] : To be updated..."),
    Interjection("Placeholder [interjection] : To be updated..."),
    Noun("Placeholder [noun] : To be updated..."),
    Preposition("Placeholder [preposition] : To be updated..."),
    Pronoun("Placeholder [pronoun] : To be updated..."),
    Verb("Placeholder [verb] : To be updated...");


    private String speechValue;

    private PartsOfSpeech(String speechValue) {
        this.speechValue= speechValue;
    }

    public String getSpeechValue() {
        return speechValue;
    }

}
public class Dictionary {
    public static void main(String args[]) {
        System.out.println("! Loading data...");
        Map<String, List<String>> dictionaryMap = new HashMap<String, List<String>>();

        List<String> POSList = new ArrayList<>();

        POSList.add(PartsOfSpeech.Adjective.getSpeechValue());
        POSList.add(PartsOfSpeech.Adverb.getSpeechValue());
        POSList.add(PartsOfSpeech.Conjunction.getSpeechValue());
        POSList.add(PartsOfSpeech.Interjection.getSpeechValue());
        POSList.add(PartsOfSpeech.Noun.getSpeechValue());
        POSList.add(PartsOfSpeech.Preposition.getSpeechValue());
        POSList.add(PartsOfSpeech.Pronoun.getSpeechValue());
        POSList.add(PartsOfSpeech.Verb.getSpeechValue());

        dictionaryMap.put("distinct",POSList);

最佳答案

values() 方法返回枚举值的数组。您可以迭代这些值,获取语音值,并将它们添加到列表中。

以下是如何使用 Stream API 执行上述操作:

List<String> POSList = Arrays.stream(PartsOfSpeech.values())
        .map(PartsOfSpeech::getSpeechValue)
        .collect(Collectors.toList());

按照 Java 命名约定,它应该是 posList 而不是 POSList

关于java - 尝试从枚举类创建字符串的 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54739608/

相关文章:

java - C++ 列出用法

c++ - 如何知道传递给函数的参数是 C++ 中的类、 union 还是枚举?

java - 如何在 Java 中从 XML 读取特殊字符的映射?

java - 为什么ArrayList的非静态内部类SubList有一个成员变量 "parent"?

java - 在 ArrayList 中搜索对象

swift - 不确定在 swift 中使用什么数据类型

java - 根据类ID创建实例

java - 如何在 Java 中以安全的方式停止和恢复线程?

java - 属性文件中的逗号分隔列表作为 Spring Bean 中的构造函数参数

java - Java 的 String.GetBytes(Charset) 中的 UTF-8