263

最近、私は同僚と、Javaで変換するための最適な方法は何か、ListそしてMapそうすることの特定の利点があるかどうかについて話し合っています。

最適な変換アプローチを知りたいので、誰かが私を導いてくれたら本当にありがたいです。

これは良いアプローチですか:

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

18 に答える 18

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

getKey()もちろん、各アイテムには適切なタイプのキーを返すメソッドがあると仮定します。

于 2010-11-09T20:45:06.210 に答える
115

この質問が重複して閉じられていない場合に備えて、正しい答えは Google Collections を使用することです:

Map<String,Role> mappedRoles = Maps.uniqueIndex(yourList, new Function<Role,String>() {
  public String apply(Role from) {
    return from.getName(); // or something else
  }});
于 2011-12-15T09:32:44.940 に答える
17

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);
于 2014-10-27T18:40:39.390 に答える
10

AListMapは概念的に異なります。AListはアイテムの順序付きコレクションです。アイテムには重複が含まれる可能性があり、アイテムには一意の識別子 (キー) の概念がない場合があります。AMapには、キーにマップされた値があります。各キーは 1 つの値のみを指すことができます。

そのため、Listのアイテムによっては、 に変換できる場合とできない場合がありますMapListさんのアイテムに重複はありませんか? 各アイテムには一意のキーがありますか? もしそうなら、それらを に入れることが可能Mapです。

于 2010-11-09T20:52:57.743 に答える
8

Google ライブラリのMaps.uniqueIndex(...)を使用してこれを行う簡単な方法もあります。

于 2012-04-02T22:17:31.860 に答える
5

普遍的な方法

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);
}
于 2011-11-23T23:10:48.303 に答える
4

Java-8 がなければ、1 行の 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);
        }
    });
}};
于 2015-05-15T15:00:25.047 に答える
2

達成したいことに応じて、多くの解決策が思い浮かびます。

すべてのリストアイテムは重要で価値があります

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));
}

..。

それは本当にあなたが達成したいものに依存します。

例からわかるように、マップはキーから値へのマッピングですが、リストはそれぞれが位置を持つ一連の要素にすぎません。したがって、それらは単に自動的に変換可能ではありません。

于 2010-11-09T20:49:46.140 に答える
2

これはまさにこの目的のために私が書いた小さな方法です。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;
}
于 2011-07-14T14:00:02.100 に答える
0

Kango_V の回答は気に入っていますが、複雑すぎると思います。これはもっと単純だと思います-単純すぎるかもしれません。気が向いたら、String を Generic マーカーに置き換えて、どの Key タイプでも機能させることができます。

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();
                    }
                } );
于 2011-09-20T15:42:39.637 に答える