欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

List -> Map> demo java 8StreamListMap 

程序员文章站 2022-07-12 18:33:00
...
package com.ctrip.framework.apollo.demo;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maxiaolong
 * @create 2018-07-17 10:12
 **/
public class StreamDemo {

  public static void main (String[] args) {
    convert();
  }

  private static void convert () {
    List<Bean> beanList = Lists.newArrayList(new Bean("k1", "f1", "v1"),
            new Bean("k1", "f2", "v2"), new Bean("k2", "f2", "v3"));
    Map<String, Map<String, String>> resultMap = beanList.stream().collect(Collectors.toMap(bean -> bean.getKey(),
            bean -> {
              Map map = Maps.newHashMap();
              map.put(bean.getField(), bean.getValue());
              return map;
            }, (oldValue, newValue) -> {
                oldValue.putAll(newValue);
                return oldValue;
            }));
    resultMap.forEach((key, value) -> System.out.println("key: " + key + "; value: " + value));
  }

  static class Bean {

    private String key;

    private String field;

    private String value;

    public Bean (String key, String field, String value) {
      this.key = key;
      this.value = value;
      this.field = field;
    }

    public String getKey() {
      return key;
    }

    public void setKey(String key) {
      this.key = key;
    }

    public String getField() {
      return field;
    }

    public void setField(String field) {
      this.field = field;
    }

    public String getValue() {
      return value;
    }

    public void setValue(String value) {
      this.value = value;
    }
  }

}