java8 Stream 函数式编程 lambda
数据流获取
List<Character> list = Arrays.asList('a', 'b', 'c', 'd', 'e');
list.stream();
或者
Stream.of('a', 'b', 'c', 'd', 'e');
Stream and Collectors
1.过滤比 ‘b’ 大的字符子集,以linkedList 返回
List<String> collect = Stream.of("a", "b", "c", "d", "e").
filter(e -> e.charAt(0) > 'b')
.collect(Collectors.toCollection(LinkedList::new));
2.把集合 按照是否比‘b‘大进行分组,以TreeMap 接收,分组后的元素用List收集。groupingby可以多层嵌套
TreeMap<Boolean, List<String>> collect = Stream.of("a", "b", "c", "d", "e")
.collect(Collectors.groupingBy(e -> e.charAt(0) > 'c'
, TreeMap::new
, Collectors.toList()));
3.统计集合中元素的个数
Long collect = Stream.of("a", "b", "c", "d", "e").collect(Collectors.counting());
4.字符串拼接 Reduce,流处理的输入和输出类型保持一致
String collect = Stream.of("a", "b", "c", "d", "e")
.collect(Collectors.reducing("begin", String::concat));
或者
String collect = Stream.of("a", "b", "c", "d", "e")
.reduce("begin",String::concat);
5.对每个元素做无返回值的处理(例如 打印元素),并且拼接字符串
String collect = Stream.of("a", "b", "c", "d", "e")
.peek(System.out::println).collect(Collectors.joining());
6.获取元组中最大值
String collect = Stream.of("a", "b", "c", "d", "e")
.collect(Collectors.maxBy(String::compareTo)).get();
7.两步处理,先聚合获取Optional<String>,再使用第一步的结果 Optional.get()
String collect = Stream.of("a", "b", "c", "d", "e")
.collect(Collectors.collectingAndThen(
Collectors.reducing(String::concat), Optional::get));
Optional
使用Optional 可以极大得美化判空语句和各种条件判断。你值得拥有
1.如果有值则使用该值,无返回值
Optional.ofNullable((String)"hellworld").ifPresent(System.out::println);
2.如果有值就返回该值,如果该值为null,则使用后者
String s2 = Optional.ofNullable((String) null).orElseGet(() -> "instaead");
或者
String s2 = Optional.ofNullable((String) null).orElse("instead")
3.如果有值则返回,否则抛出异常
String s2 = Optional.ofNullable((String) null).orElseThrow(RuntimeException::new);
4.判断值是否为空
Boolean s2 = Optional.ofNullable((String) null).isPresent();
5.对象映射 自动包装map 手动包装flatMap
Optional<Boolean> op1 = Optional.ofNullable((String) "null")
.flatMap(e -> Optional.of(e.isEmpty()));
Optional<Boolean> op2 = Optional.ofNullable((String) "null")
.map(e -> e.isEmpty());