Java: How to convert List to Map

2019-01-01 10:32发布

Recently I have conversation with a colleague about what would be the optimal way to convert List to Map in Java and if there any specific benefits of doing so.

I want to know optimal conversion approach and would really appreciate if any one can guide me.

Is this good approach:

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

16条回答
无与为乐者.
2楼-- · 2019-01-01 10:57

There is also a simple way of doing this using Maps.uniqueIndex(...) from Google libraries

查看更多
唯独是你
3楼-- · 2019-01-01 10:58

Using Java 8 you can do following :

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

Value can be any object you use.

查看更多
初与友歌
4楼-- · 2019-01-01 10:58

Without java-8, you'll be able to do this in one line Commons collections, and the Closure class

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);
        }
    });
}};
查看更多
谁念西风独自凉
5楼-- · 2019-01-01 10:58

Alexis has already posted an answer in Java 8 using method toMap(keyMapper, valueMapper). As per doc for this method implementation:

There are no guarantees on the type, mutability, serializability, or thread-safety of the Map returned.

So in case we are interested in a specific implementation of Map interface e.g. HashMap then we can use the overloaded form as:

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

Though using either Function.identity() or i->i is fine but it seems Function.identity() instead of i -> i might save some memory as per this related answer.

查看更多
若你有天会懂
6楼-- · 2019-01-01 10:59

A Java 8 example to convert a List<?> of objects into a 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()));

Code copied from:
https://www.mkyong.com/java8/java-8-convert-list-to-map/

查看更多
心情的温度
7楼-- · 2019-01-01 11:01

Just in case this question isn't closed as a duplicate, the right answer is to use Google Collections:

Map<String,Role> mappedRoles = Maps.uniqueIndex(yourList, new Function<Role,String>() {
  public String apply(Role from) {
    return from.getName(); // or something else
  }});
查看更多
登录 后发表回答