最近,我和一位同事讨论了在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]);
}
Alexis已经在Java 8中使用toMap方法(keyMapper, valueMapper)发布了一个答案。根据这个方法实现的文档:
没有对类型、可变性、可序列化性或
返回Map的线程安全。
因此,如果我们对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可能会根据这个相关的答案节省一些内存。
Apache Commons MapUtils.populateMap
如果您不使用Java 8,并且出于某种原因不想使用显式循环,可以尝试MapUtils。populateMap来自Apache Commons。
MapUtils.populateMap
假设您有一个巴黎的列表。
List<ImmutablePair<String, String>> pairs = ImmutableList.of(
new ImmutablePair<>("A", "aaa"),
new ImmutablePair<>("B", "bbb")
);
现在需要Pair对象的Pair键的Map。
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);
您可以利用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/
这是我为这个目的写的一个小方法。它使用来自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中,我们有收藏家的简洁解决方案:
list.stream().collect(
groupingBy(Item::getKey)
)
同时,你可以通过另一个groupingBy方法作为第二个参数来嵌套多个组:
list.stream().collect(
groupingBy(Item::getKey, groupingBy(Item::getOtherKey))
)
这样,我们就有了多级映射,就像这样:map <key, map <key, List<Item>>>