Попытка создать ArrayList of Strings из класса enum
Мне удалось успешно загрузить мой ArrayList из значений класса enum. Я не очень знаком с использованием перечислений, и мне было интересно, есть ли способ справиться с этим, не вводя 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 ответ
Решение
values()
Метод возвращает массив значений enum. Вы можете перебирать эти значения, получать речевое значение и добавлять их в список.
Вот как вы можете сделать это с помощью Stream API:
List<String> POSList = Arrays.stream(PartsOfSpeech.values())
.map(PartsOfSpeech::getSpeechValue)
.collect(Collectors.toList());
И в соответствии с соглашением об именах Java, это должно быть posList
и не POSList
,