天天看點

List -> Map<String, Map<String, Striing>> demo

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;
    }
  }

}