为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

呼如林 2022-06-23 16:14:09
我已经能够从枚举类的值中成功加载我的 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);
查看完整描述

1 回答

?
慕勒3428872

TA贡献1848条经验 获得超6个赞

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

以下是使用 Stream API 执行上述操作的方法:

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

并且遵循 Java 命名约定,它应该是posList而不是POSList.


查看完整回答
反对 回复 2022-06-23
  • 1 回答
  • 0 关注
  • 131 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号