Utility to convert List to Map

Kathir :

We can convert a list to map using the following

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

Is there is a java or apache common utility which does in a single line? Some times the key should be sequential integer, sometimes the key is the value itself (taking care of uniqueness).

Robby Cornelissen :

You can use the toMap() collector with a stream:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11771&siteId=1