java8 Stream函数式

rt,比如有个ArrayList a,泛型为B,我想去判断如果B中某个字段(假如getFieldX)不为null,执行一种操作,为null执行另一种,请问框架怎么写?要函数式那种

红糖糍粑
浏览 410回答 2
2回答

手掌心

List<Person> list = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; list.addAll(Arrays.asList(new Person("a"), new Person("b"), new Person(), new Person("c"), new Person()));&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; list = list.stream()//创建stream&nbsp; &nbsp; &nbsp; &nbsp; .map((p) -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (p.getName() == null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //为空时执行的操作&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; p.setName("hello");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //不为空要执行的操作&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; p.setName(null);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return p;&nbsp; &nbsp; &nbsp; &nbsp; })//转换stream,返回值仍为stream。所有转换strem操作为惰性,直到调用汇聚函数才一并执行,&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());//汇聚函数,计算结果返回为List类型&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(list);

HUWWW

函数式?你指的是lambda表达式?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java