List转Map
  1. //方法一
  2. Map<Integer, GoodsVO> map = goodsListForWhale.stream()
  3. .collect(Collectors.toMap(GoodsVO::getId, h -> h));
  4. //方法二
  5. Map<Integer, GoodsVO> map = goodsListForWhale.stream()
  6. .collect(Collectors.groupingBy(GoodsVO::getId,
  7. Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0))));

List转Map

抽取对象的code作为key,name作为value转化为map集合。

  1. private static HashMap<String, String> listToMap(List<Person> personList) {
  2. return (HashMap<String, String>)personList.stream()
  3. .filter(t -> t.getName()!=null)
  4. .collect(Collectors.toMap(Person::getCode,Person::getName,(k1,k2)->k2));
  5. }

filter() 方法作用是过滤掉名字为空的对象,当对象的名字为null时,会出现NPE空指针异常
(k1,k2)->k2 意思是遇到相同的key时取第二个值
(k1,k2)->k1 意思是遇到相同的key时取第一个值

List转Map>

根据某个字段分组。

  1. Map<String, List<Map>> lableGbType =
  2. list.stream().collect(Collectors.groupingBy(l -> (String) l.get("id")));

List根据对象的属性进行去重
  1. //对集合的结果进行去重
  2. //根据userid 去重
  3. List<User> list = userList.stream()
  4. .collect(Collectors.collectingAndThen(
  5. Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User::getUserId)))
  6. ,ArrayList::new));
  7. System.out.println(list);

32个Java Stream案例

32个Java Stream案例