// 普通写法
List<Long> dataIds = dataMap.get(data.getFileId());
if (CollectionUtil.isNotEmpty(dataIds)) {
for (Long id : dataIds) {
result.put(id, “test”);
}
}
//Optional配合lambada
Optional.ofNullable(dataMap.get(data.getFileId()))
.ifPresent(dataIds ->dataIds.forEach(id -> result.put(id, “test”)));
2.多层null判断
public class TestMain {
@Data
public static class Person{
public Integer id;
public Person(){}
}
@Data
public static class Child {
public Person person;
}
@Data
public static class Parent{
public Child child;
}
public static void main(String[] args) {
Person person = new Person();
person.setId(1);
Child child = new Child();
child.setPerson(person);
Parent parent = new Parent();
parent.setChild(child);
//普通写法
Integer id = null;
if(parent != null && parent.getChild() != null && parent.getChild().getPerson() != null){
id = parent.getChild().getPerson().getId();
}
System.out.println(id);
//Optional写法
Integer id2 = null;
id2 = Optional.ofNullable(parent)
.map(Parent::getChild)
.map(Child::getPerson)
.map(Person::getId)
.orElse(null);
System.out.println(id2);
}
3.初始化
List<String> list = null;
list = Optional.ofNullable(list).orElseGet(ArrayList::new);