java_Stream

248 阅读2分钟

Optional

  • String customerName= Optional.ofNullable(name).orElse("匿名"):如果name字段是空的则返回匿名

  • Optional.ofNullable(certs).map(CertEntity::getName).orElse("其他"):如果certs是空的,则跳过map,执行后面的orElse;如果certs不是空的,则提取name属性的值并返回

创建Stream流

  • 单列集合:集合对象.stream()

  • 数组:Arrays.stream(数组)

  • 双列集合:转换成entrySet再创建

    Map<String,Integer> map = new HashMap<>();
    map.put("张三",17);
    map.put("向阳",16);
    
    Stream<Map.Entry<String, Integer>> stream = map.entrySet().stream();
    

中间操作

map
authors.stream().map(s -> s.getName()).forEach(s -> System.out.println(s));
mapToInt

将流中的元素从Integer类型转换成int类型,避免每次自动拆箱、自动装箱,提升效率,mapToLong,mapToDouble,flatMapToInt,flatMapToDouble同理

flatMap

把List中的元素或数组中的元素解放出来成为流中的元素

authors.stream()
    .flatMap(author -> author.getBooks().stream())
    .distinct()
    .flatMap(book -> Arrays.stream(book.getCategory().split(",")))
    .distinct()
    .forEach(category-> System.out.println(category));
peek

对流中元素执行指定操作

sort
  • 空参方法需要流中元素实现Comparable接口
  • 非空参方法需要写函数式接口(lambda或Comparator.comparing)

空参方法

authors.stream()
    .sorted()   
    .forEach(author -> System.out.println(author.getAge()));

lambda

authors.stream()
       .sorted((o1,o2) -> o1.getName().compareTo(o2.getName())
       .collect(Collectors.toList()
);

空字段排序

list.stream().sorted(
    Comparator.comparing(User::getProvincePriority, Comparator.nullsLast(Integer::compareTo))
).collect(Collectors.toList());

先按年龄倒序,然后相同年龄再按生日倒序

list.stream().sorted(
     Comparator.comparing(User::getAge, Comparator.reverseOrder())
    .thenComparing(User::getBirthday,Comparator.reverseOrder())
).collect(Collectors.toList());
parallelStream

直接获取并行流,一步到位

authors.parallelStream()
    .map(author -> author.getAge())
    .map(age -> age + 10)
    .filter(age->age>18)
    .map(age->age+2)
    .forEach(System.out::println);

终结操作

collect

获取Map集合,map中key为作者名,value为List<Book>

Map<String, List<Book>> authorList = authors.stream()
    .distinct()
    .collect(Collectors.toMap(Author::getName, Author::getBooks));

toMap()最少接收两个参数,这个方法碰到重复的key会抛出异常,这时可以通过第三个参数来解决重复key的问题

Map<Integer, String> map = list.stream()   // 新的value值覆盖旧的value值
    .collect(Collectors.toMap(Person::getId, Person::getName, (oldValue, newValue) -> newValue));
groupingBy

详见另一篇文章:《stream之grouping by》

count
// 打印所有作家的书籍数量
long count = authors.stream()
    .flatMap(s -> s.getBooks().stream())
    .distinct()
    .count();
System.out.println(count);
max min
Optional<Book> maxScoreBook = authors.stream()
    .flatMap(s -> s.getBooks().stream())
    .max((book1, book2) -> book1.getScore() - book2.getScore());
reduce

用来进行计算,接受两个参数,一个初始值和一个运算操作

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

int sum = numbers.stream().reduce(0, (a, b) -> a + b);

System.out.println(sum);  // 输出:15

findirst

// 获取年龄最小的作家,并输出他的名字
Optional<Author> first = authors.stream()
    .sorted((o1, o2) -> o1.getAge() - o2.getAge())
    .findFirst();
first.ifPresent(author -> System.out.println(author.getName()));
anyMatch

是否有一个符合条件的元素,有一个满足则为true,否则为false

allMatch

所有元素是否都符合指定条件,都符合为true,否则为false

// 判断是否所有的作家都是成年人
boolean flag = authors.stream()
    .allMatch(author -> author.getAge() >= 18);
System.out.println(flag);
noneMatch

所有元素是否都不符合指定条件,都不符合结果为true,否则为false

// 判断作家是否都没有超过100岁的。
boolean flag = authors.stream()
    .noneMatch(author -> author.getAge() > 100);