[java] Java 8 List <V>를 Map <K, V>로

Java 8의 스트림과 람다를 사용하여 객체 목록을 Map으로 변환하고 싶습니다.

이것이 Java 7 이하에서 작성하는 방법입니다.

private Map<String, Choice> nameMap(List<Choice> choices) {
        final Map<String, Choice> hashMap = new HashMap<>();
        for (final Choice choice : choices) {
            hashMap.put(choice.getName(), choice);
        }
        return hashMap;
}

Java 8 및 Guava를 사용하여 쉽게 수행 할 수 있지만 Guava 없이이 작업을 수행하는 방법을 알고 싶습니다.

구아바에서 :

private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, new Function<Choice, String>() {

        @Override
        public String apply(final Choice input) {
            return input.getName();
        }
    });
}

Java 8 람다가있는 구아바.

private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, Choice::getName);
}



답변

Collectors문서를 기반 으로 다음과 같이 간단합니다.

Map<String, Choice> result =
    choices.stream().collect(Collectors.toMap(Choice::getName,
                                              Function.identity()));


답변

키가 목록의 모든 요소에 대해 고유 하지 않다고 보장하는 경우 키 Map<String, List<Choice>>대신Map<String, Choice>

Map<String, List<Choice>> result =
 choices.stream().collect(Collectors.groupingBy(Choice::getName));


답변

사용 getName()키와 같은 Choice맵의 값 자체 :

Map<String, Choice> result =
    choices.stream().collect(Collectors.toMap(Choice::getName, c -> c));


답변

Collectors.toMap ()을 사용하지 않으려는 경우를위한 또 다른 방법이 있습니다.

Map<String, Choice> result =
   choices.stream().collect(HashMap<String, Choice>::new, 
                           (m, c) -> m.put(c.getName(), c),
                           (m, u) -> {});


답변

나열된 답변의 대부분은 목록에 항목이 중복 된 경우를 놓치십시오 . 이 경우 답변이 발생 IllegalStateException합니다. 목록 중복처리 하려면 아래 코드 참조하십시오 .

public Map<String, Choice> convertListToMap(List<Choice> choices) {
    return choices.stream()
        .collect(Collectors.toMap(Choice::getName, choice -> choice,
            (oldValue, newValue) -> newValue));
  }


답변

간단한 방법으로 하나 더 옵션

Map<String,Choice> map = new HashMap<>();
choices.forEach(e->map.put(e.getName(),e));


답변

예를 들어, 오브젝트 필드를 맵으로 변환하려면 다음을 수행하십시오.

예제 개체 :

class Item{
        private String code;
        private String name;

        public Item(String code, String name) {
            this.code = code;
            this.name = name;
        }

        //getters and setters
    }

그리고 작업 목록을 맵으로 변환 :

List<Item> list = new ArrayList<>();
list.add(new Item("code1", "name1"));
list.add(new Item("code2", "name2"));

Map<String,String> map = list.stream()
     .collect(Collectors.toMap(Item::getCode, Item::getName));