Programming

Java : List를 Map으로 변환하는 방법

procodes 2020. 5. 9. 16:59
반응형

Java : List를 Map으로 변환하는 방법


최근에 나는 변환 할 수있는 최적의 방법이 될 것이다 대해 동료와 대화를 ListMap자바와 경우가 그렇게하는 특정 혜택을 제공합니다.

최적의 전환 접근 방식을 알고 싶습니다.

이 좋은 접근법입니까?

List<Object[]> results;
Map<Integer, String> resultsMap = new HashMap<Integer, String>();
for (Object[] o : results) {
    resultsMap.put((Integer) o[0], (String) o[1]);
}

List<Item> list;
Map<Key,Item> map = new HashMap<Key,Item>();
for (Item i : list) map.put(i.getKey(),i);

물론 각 Item getKey()에 적절한 유형의 키를 반환하는 메서드 가 있다고 가정 합니다.


함께 , 당신은 하나 개를 사용하여 라인에서이 작업을 수행 할 수 있습니다 스트림을 , 그리고 Collectors클래스입니다.

Map<String, Item> map = 
    list.stream().collect(Collectors.toMap(Item::getKey, item -> item));

짧은 데모 :

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Test{
    public static void main (String [] args){
        List<Item> list = IntStream.rangeClosed(1, 4)
                                   .mapToObj(Item::new)
                                   .collect(Collectors.toList()); //[Item [i=1], Item [i=2], Item [i=3], Item [i=4]]

        Map<String, Item> map = 
            list.stream().collect(Collectors.toMap(Item::getKey, item -> item));

        map.forEach((k, v) -> System.out.println(k + " => " + v));
    }
}
class Item {

    private final int i;

    public Item(int i){
        this.i = i;
    }

    public String getKey(){
        return "Key-"+i;
    }

    @Override
    public String toString() {
        return "Item [i=" + i + "]";
    }
}

산출:

Key-1 => Item [i=1]
Key-2 => Item [i=2]
Key-3 => Item [i=3]
Key-4 => Item [i=4]

의견에서 언급했듯이 다소 명시 적으로 보이지만 Function.identity()대신 대신 사용할 수 있습니다 .item -> itemi -> i

그리고 함수가 형용사가 아닌 경우 이진 연산자를 사용할 수 있습니다. 예를 들어 이것을 Listint 값의 경우 모듈로 3의 결과를 계산하는 매핑 함수를 고려해 봅시다 .

List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 6);
Map<String, Integer> map = 
    intList.stream().collect(toMap(i -> String.valueOf(i % 3), i -> i));

이 코드를 실행하면 오류 메시지가 나타납니다 java.lang.IllegalStateException: Duplicate key 1. 이는 1 % 3이 4 % 3과 같기 때문에 키 매핑 기능에서 동일한 키 값을 갖기 때문입니다. 이 경우 병합 연산자를 제공 할 수 있습니다.

다음은 값을 합한 것입니다. (i1, i2) -> i1 + i2;메소드 참조로 대체 할 수 있습니다 Integer::sum.

Map<String, Integer> map = 
    intList.stream().collect(toMap(i -> String.valueOf(i % 3), 
                                   i -> i, 
                                   Integer::sum));

이제 출력 :

0 => 9 (i.e 3 + 6)
1 => 5 (i.e 1 + 4)
2 => 7 (i.e 2 + 5)

그것이 도움이되기를 바랍니다! :)


이 질문이 중복되지 않은 경우 Google 답변을 사용하는 것이 정답입니다 .

Map<String,Role> mappedRoles = Maps.uniqueIndex(yourList, new Function<Role,String>() {
  public String apply(Role from) {
    return from.getName(); // or something else
  }});

Java 8부터 콜렉터를 사용한 @ZouZou대답Collectors.toMap 은 확실히이 문제를 해결하는 관용적 방법입니다.

그리고 이것은 일반적인 작업이므로 정적 유틸리티로 만들 수 있습니다.

그렇게하면 솔루션이 진정으로 하나의 라이너가됩니다.

/**
 * Returns a map where each entry is an item of {@code list} mapped by the
 * key produced by applying {@code mapper} to the item.
 *
 * @param list the list to map
 * @param mapper the function to produce the key from a list item
 * @return the resulting map
 * @throws IllegalStateException on duplicate key
 */
public static <K, T> Map<K, T> toMapBy(List<T> list,
        Function<? super T, ? extends K> mapper) {
    return list.stream().collect(Collectors.toMap(mapper, Function.identity()));
}

그리고 여기에 사용하는 방법이 있습니다 List<Student>:

Map<Long, Student> studentsById = toMapBy(students, Student::getId);

Java 8을 사용하면 다음을 수행 할 수 있습니다.

Map<Key, Value> result= results
                       .stream()
                       .collect(Collectors.toMap(Value::getName,Function.identity()));

Value 사용하는 모든 객체가 될 수 있습니다.


List과는 Map다른 개념이다. A List는 주문한 항목 모음입니다. 항목에는 중복 항목이 포함될 수 있으며 항목에는 고유 식별자 (키) 개념이 없을 수 있습니다. A Map에는 키에 매핑 된 값이 있습니다. 각 키는 하나의 값만 가리킬 수 있습니다.

따라서 귀하 List의 항목 에 따라 로 변환하거나 변환하지 못할 수 있습니다 Map. List의 항목에 중복 항목이 없습니까? 각 항목에 고유 키가 있습니까? 그렇다면을에 넣을 수 있습니다 Map.


Google 라이브러리의 Maps.uniqueIndex (...)사용 하여이 작업을 수행하는 간단한 방법도 있습니다


Alexis는 이미 method를 사용하여 Java 8에 답변을 게시했습니다 toMap(keyMapper, valueMapper). 이 메소드 구현에 대한 doc따라 :

리턴 된 맵의 유형, 변경 가능성, 직렬화 가능성 또는 스레드 안전성에 대한 보장은 없습니다.

따라서 Map인터페이스 의 특정 구현에 관심이있는 경우 HashMap들어 오버로드 된 형식을 다음과 같이 사용할 수 있습니다.

Map<String, Item> map2 =
                itemList.stream().collect(Collectors.toMap(Item::getKey, //key for map
                        Function.identity(),    // value for map
                        (o,n) -> o,             // merge function in case of conflict with keys
                        HashMap::new));         // map factory - we want HashMap and not any Map implementation

사용 중 하나지만 Function.identity()나하는 것은 i->i괜찮지 만 보인다 Function.identity()대신 i -> i이 관련에 따라 일부 메모리 저장 힘 대답 .


보편적 인 방법

public static <K, V> Map<K, V> listAsMap(Collection<V> sourceList, ListToMapConverter<K, V> converter) {
    Map<K, V> newMap = new HashMap<K, V>();
    for (V item : sourceList) {
        newMap.put( converter.getKey(item), item );
    }
    return newMap;
}

public static interface ListToMapConverter<K, V> {
    public K getKey(V item);
}

java-8이 없으면 Commons 컬렉션 한 줄과 Closure 클래스 에서이 작업을 수행 할 수 있습니다

List<Item> list;
@SuppressWarnings("unchecked")
Map<Key, Item> map  = new HashMap<Key, Item>>(){{
    CollectionUtils.forAllDo(list, new Closure() {
        @Override
        public void execute(Object input) {
            Item item = (Item) input;
            put(i.getKey(), item);
        }
    });
}};

달성하려는 대상에 따라 많은 솔루션이 떠 오릅니다.

모든 목록 항목은 키와 가치입니다

for( Object o : list ) {
    map.put(o,o);
}

목록 요소에는 찾아 볼 항목이있을 수 있습니다 (아마 이름).

for( MyObject o : list ) {
    map.put(o.name,o);
}

목록 요소에는 찾아야 할 요소가 있으며 고유하다는 보장은 없습니다. Google 멀티 맵 사용

for( MyObject o : list ) {
    multimap.put(o.name,o);
}

모든 요소에 위치를 키로 제공 :

for( int i=0; i<list.size; i++ ) {
    map.put(i,list.get(i));
}

...

그것은 당신이 무엇을 원하느냐에 달려 있습니다.

예제에서 볼 수 있듯이 맵은 키에서 값으로의 매핑이며 목록은 각각 위치를 갖는 일련의 요소입니다. 따라서 단순히 자동으로 변환 할 수 없습니다.


이 목적을 위해 내가 쓴 작은 방법이 있습니다. Apache Commons의 Validate를 사용합니다.

자유롭게 사용하십시오.

/**
 * Converts a <code>List</code> to a map. One of the methods of the list is called to retrive
 * the value of the key to be used and the object itself from the list entry is used as the
 * objct. An empty <code>Map</code> is returned upon null input.
 * Reflection is used to retrieve the key from the object instance and method name passed in.
 *
 * @param <K> The type of the key to be used in the map
 * @param <V> The type of value to be used in the map and the type of the elements in the
 *            collection
 * @param coll The collection to be converted.
 * @param keyType The class of key
 * @param valueType The class of the value
 * @param keyMethodName The method name to call on each instance in the collection to retrieve
 *            the key
 * @return A map of key to value instances
 * @throws IllegalArgumentException if any of the other paremeters are invalid.
 */
public static <K, V> Map<K, V> asMap(final java.util.Collection<V> coll,
        final Class<K> keyType,
        final Class<V> valueType,
        final String keyMethodName) {

    final HashMap<K, V> map = new HashMap<K, V>();
    Method method = null;

    if (isEmpty(coll)) return map;
    notNull(keyType, Messages.getString(KEY_TYPE_NOT_NULL));
    notNull(valueType, Messages.getString(VALUE_TYPE_NOT_NULL));
    notEmpty(keyMethodName, Messages.getString(KEY_METHOD_NAME_NOT_NULL));

    try {
        // return the Method to invoke to get the key for the map
        method = valueType.getMethod(keyMethodName);
    }
    catch (final NoSuchMethodException e) {
        final String message =
            String.format(
                    Messages.getString(METHOD_NOT_FOUND),
                    keyMethodName,
                    valueType);
        e.fillInStackTrace();
        logger.error(message, e);
        throw new IllegalArgumentException(message, e);
    }
    try {
        for (final V value : coll) {

            Object object;
            object = method.invoke(value);
            @SuppressWarnings("unchecked")
            final K key = (K) object;
            map.put(key, value);
        }
    }
    catch (final Exception e) {
        final String message =
            String.format(
                    Messages.getString(METHOD_CALL_FAILED),
                    method,
                    valueType);
        e.fillInStackTrace();
        logger.error(message, e);
        throw new IllegalArgumentException(message, e);
    }
    return map;
}

Java 8의 스트림 API를 활용할 수 있습니다.

public class ListToMap {

  public static void main(String[] args) {
    List<User> items = Arrays.asList(new User("One"), new User("Two"), new User("Three"));

    Map<String, User> map = createHashMap(items);
    for(String key : map.keySet()) {
      System.out.println(key +" : "+map.get(key));
    }
  }

  public static Map<String, User> createHashMap(List<User> items) {
    Map<String, User> map = items.stream().collect(Collectors.toMap(User::getId, Function.identity()));
    return map;
  }
}

자세한 내용은 http://codecramp.com/java-8-streams-api-convert-list-map/을 참조하십시오.


이미 말했듯이 Java-8에서는 Collectors의 간결한 솔루션이 있습니다.

  list.stream().collect(
         groupingBy(Item::getKey)
        )

또한 다른 groupingBy 메소드를 두 번째 매개 변수로 전달하여 여러 그룹을 중첩 할 수 있습니다.

  list.stream().collect(
         groupingBy(Item::getKey, groupingBy(Item::getOtherKey))
        )

이런 식으로 다음과 같이 다중 레벨 맵을 갖게됩니다. Map<key, Map<key, List<Item>>>


List<?>객체를 다음으로 변환하는 Java 8 예제 Map<k, v>:

List<Hosting> list = new ArrayList<>();
list.add(new Hosting(1, "liquidweb.com", new Date()));
list.add(new Hosting(2, "linode.com", new Date()));
list.add(new Hosting(3, "digitalocean.com", new Date()));

//example 1
Map<Integer, String> result1 = list.stream().collect(
    Collectors.toMap(Hosting::getId, Hosting::getName));

System.out.println("Result 1 : " + result1);

//example 2
Map<Integer, String> result2 = list.stream().collect(
    Collectors.toMap(x -> x.getId(), x -> x.getName()));

https://www.mkyong.com/java8/java-8-convert-list-to-map/ 에서 복사 한 코드


Kango_V의 답변이 마음에 들지만 너무 복잡하다고 생각합니다. 나는 이것이 더 간단하다고 생각합니다-아마도 너무 간단합니다. 기울어지면 문자열을 일반 마커로 바꾸고 모든 키 유형에 사용할 수 있습니다.

public static <E> Map<String, E> convertListToMap(Collection<E> sourceList, ListToMapConverterInterface<E> converterInterface) {
    Map<String, E> newMap = new HashMap<String, E>();
    for( E item : sourceList ) {
        newMap.put( converterInterface.getKeyForItem( item ), item );
    }
    return newMap;
}

public interface ListToMapConverterInterface<E> {
    public String getKeyForItem(E item);
}

이런 식으로 사용 :

        Map<String, PricingPlanAttribute> pricingPlanAttributeMap = convertListToMap( pricingPlanAttributeList,
                new ListToMapConverterInterface<PricingPlanAttribute>() {

                    @Override
                    public String getKeyForItem(PricingPlanAttribute item) {
                        return item.getFullName();
                    }
                } );

Apache Commons MapUtils.populateMap

Java 8을 사용하지 않고 어떤 이유로 명시 적 루프를 사용하지 않으려면 MapUtils.populateMapApache Commons에서 시도하십시오 .

MapUtils.populateMap

의 목록이 있다고 가정하십시오 Pair.

List<ImmutablePair<String, String>> pairs = ImmutableList.of(
    new ImmutablePair<>("A", "aaa"),
    new ImmutablePair<>("B", "bbb")
);

그리고 이제 객체 Pair에 대한 키 맵을 원합니다 Pair.

Map<String, Pair<String, String>> map = new HashMap<>();
MapUtils.populateMap(map, pairs, new Transformer<Pair<String, String>, String>() {

  @Override
  public String transform(Pair<String, String> input) {
    return input.getKey();
  }
});

System.out.println(map);

출력을 제공합니다.

{A=(A,aaa), B=(B,bbb)}

즉, for루프는 이해하기 쉽습니다. (이것은 동일한 출력을 제공합니다) :

Map<String, Pair<String, String>> map = new HashMap<>();
for (Pair<String, String> pair : pairs) {
  map.put(pair.getKey(), pair);
}
System.out.println(map);

참고 URL : https://stackoverflow.com/questions/4138364/java-how-to-convert-list-to-map

반응형