简介
lambda简介
(参数) -> 含参数的表达式
或
(参数) ->{ 对参数进行处理的代码块 }
**注:**这个参数如果是多个,要用逗号隔开。如果是一个参数,可以省略参数的左右括号。如果没有参数,括号不能省略。
1.对象不为空
DictionaryDTO dictionaryByIdReq = dictionaryMapper.findDictionaryById(dictionaryId);
if(Objects.nonNull(dictionaryByIdReq)
2.集合添加(将一个集合遍历到另一个空集合中,此例是批量删除)
List<SpuAttributeDO> spu = spuAttributeMapper.find(dictionary);
List<Long> spuAttributeIds=new ArrayList<>();
spu.stream().filter(Objects::nonNull).forEach(o->{
spuAttributeIds.add(o.getId());
});
Integer integer = spuAttributeMapper.deleteBatchIds(spuAttributeIds);
3.集合设值(给集合中所有对象中的一个字段设值)
注:o 代表spuDOList 集合中SpuDO对象
String dictionaryName = "张三"
List<SpuDO> spuDOList = spuMapper.find(id);
spuDOList.stream().filter(Objects::nonNull).forEach(o->{
o.setAttribute(dictionaryName);
});
aBoolean = spuMapper.updateSpu(spuDOList);
4.filter()相当于if
list.stream().filter(p -> p.getAge() > 21).forEach(System.out::println);
5.遍历List
List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");
//输出:A,B,C,D,E
items.forEach(item->System.out.println(item));
//输出 : C
items.forEach(item->{
if("C".equals(item)){
System.out.println(item);
}
});
6.遍历Map
aMap.forEach( (k,v)->{System.out.println(k+" "+v);} ); //下面代码的大概意思
Map<String, Integer> items = new HashMap<>();
items.put("A", 10);
items.put("B", 20);
items.put("C", 30);
items.put("D", 40);
items.put("E", 50);
items.put("F", 60);
items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));
items.forEach((k,v)->{
System.out.println("Item : " + k + " Count : " + v);
if("E".equals(k)){
System.out.println("Hello E");
}
});