1. Optional.ofNullable(param).map(Param::getCity).map(City::getCode).map(Code::getValue).orElse("init")
2. map和 flatmap flat就是拉平. 把多层嵌套的拉成一层.
assertEquals( Optional.of(Optional.of("STRING")) ,
Optional.of("string").map(s -> Optional.of("STRING"))
);
assertEquals(Optional.of("STRING"), Optional
.of("string").flatMap(s -> Optional.of("STRING")));
原理
flatMap:内部必须返回的是Optional.
map: 对返回的item重新封装了optional
应用场景
通过下面测试类得到的结果对比可知.
当map的下游也是返回的optional时,可以直接使用FlatMap. 这样可以大面积推广optional的使用.
附录
java stream中的map和flatmap. flat就是拉平. 把多层嵌套的拉成一层.
map: Returns a stream consisting of the results of applying the given function to the elements of this stream.
flatmap: Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
public class Map_FlatMap {
List<String[]> eggs = new ArrayList<>();
@Before
public void init() {
// 第一箱鸡蛋
eggs.add(new String[]{"鸡蛋_1", "鸡蛋_1", "鸡蛋_1", "鸡蛋_1", "鸡蛋_1"});
// 第二箱鸡蛋
eggs.add(new String[]{"鸡蛋_2", "鸡蛋_2", "鸡蛋_2", "鸡蛋_2", "鸡蛋_2"});
}
// 自增生成组编号
static int group = 1;
// 自增生成学生编号
static int student = 1;
/**
* 把二箱鸡蛋分别加工成煎蛋,还是放在原来的两箱,分给2组学生
*/
@Test
public void map() {
eggs.stream()
.map(x -> Arrays.stream(x).map(y -> y.replace("鸡", "煎")))
.forEach(x -> System.out.println("组" + group++ + ":" + Arrays.toString(x.toArray())));
/*
控制台打印:------------
组1:[煎蛋_1, 煎蛋_1, 煎蛋_1, 煎蛋_1, 煎蛋_1]
组2:[煎蛋_2, 煎蛋_2, 煎蛋_2, 煎蛋_2, 煎蛋_2]
*/
}
/**
* 把二箱鸡蛋分别加工成煎蛋,然后放到一起【10个煎蛋】,分给10个学生
*/
@Test
public void flatMap() {
eggs.stream()
.flatMap(x -> Arrays.stream(x).map(y -> y.replace("鸡", "煎")))
.forEach(x -> System.out.println("学生" + student++ + ":" + x));
/*
控制台打印:------------
学生1:煎蛋_1
学生2:煎蛋_1
学生3:煎蛋_1
学生4:煎蛋_1
学生5:煎蛋_1
学生6:煎蛋_2
学生7:煎蛋_2
学生8:煎蛋_2
学生9:煎蛋_2
学生10:煎蛋_2
*/
}
}