網頁

2019/12/11

Java 8 Lambda convert List to Map

Java List<V>Map<K, V>的lambda寫法如下。

下面為被List<Item>裝載的物件類別Item

Item

public class Item {

    private Long id;
    private String name;

    public Item(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public String toString() {
        return "{id=" + id + "," + "name=" + name +  "}";
    }

    // getter setters...
}

下面使用lambda語法搭配Collectors.toMap()List<Item>集合轉為Map<Long, Item>

List itemList = Arrays.asList(
        new Item(1L, "Stone"),
        new Item(2L, "Grass"),
        new Item(3L, "Dirt"));

Map<Long, Item> itemMap = itemList.stream()
                .collect(Collectors.toMap(Item::getId, Function.identity()));

itemMap.forEach((k, v) -> {
    System.out.println("key:" + k + ", value:" + v);
});

印出結果。

key:1, value:{id=1,name=Stone}
key:2, value:{id=2,name=Grass}
key:3, value:{id=3,name=Dirt}

參考:

沒有留言:

張貼留言