Попытка создать ArrayList of Strings из класса enum - PullRequest
0 голосов
/ 18 февраля 2019

Мне удалось успешно загрузить мой 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 Ответ

0 голосов
/ 18 февраля 2019

values() метод возвращает массив значений enum.Вы можете перебрать эти значения, получить речевое значение и добавить их в список.

Вот как вы можете сделать выше, используя Stream API:

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

И следуя инструкциямСоглашение об именах Java должно быть posList, а не POSList.

...