Java并发系列:Stream的使用

Java8中的Stream通过使用串行计算和并行计算,充分利用CPU性能,打到加速得到计算结果的目的。本文主要介绍:

  • S t r e a m 中 间 状 态 \color{7f1A8A}Stream中间状态 Stream
    • distinct
    • filter
    • groupingby
    • iterate_generate
    • limit
    • map
    • max_min
    • peek
    • skip
    • sort
  • S t r e a m 结 束 状 态 \color{7f1A8A}Stream结束状态 Stream
    • collection
    • count
    • findFirst_Any
    • foreach
    • matchAll_Any_None
    • reduce
  • S t r e a m 的 各 种 集 合 转 换 \color{7f1A8A}Stream的各种集合转换 Stream
    • Array2Stream2List
    • Value2Stream
    • File2Stream
    • List2Map
    • List2Stream
    • Stream2Array
  • 本 文 源 码 \color{ff2322}本文源码 :Java_Stream

正文开始

Stream中间状态

  • distinct

long i = list.stream().distinct().count();
System.out.println(i);
//方法一
list.stream().
        filter(distinctByKey(b -> b.getClassname())).
        forEach(System.out::println);
//方法二
list.stream().collect(
        Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getAge() + ";" + o.getClassname()))),
                ArrayList::new
                )
        )
        .forEach(System.out::println);
static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
     
    Map<Object, Boolean> seen = new ConcurrentHashMap<>();
    return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
  • filter
List<Employ> l = employ.getEmploylist();
l.stream()
        .filter(employ1 -> ("宝山区" == employ1.getAddr()))
        .collect(Collectors.toList())
        .forEach(System.out::println);
  • groupingby

Student student = new Student();
List<Student> list = student.getStudentlist();
Map<Integer, List<Student>> map = list.stream().
        collect(Collectors.groupingBy(Student::getAge));

//如何打印Map
for (Integer i :map.keySet()) {
     
    System.out.println("===="+i+":=====");
    List<Student> l = map.get(i);
    for(Student ss :l){
     
        System.out.print(ss.toString()+"  -  ");
    }
    System.out.println();
}
  • iterate_generate
Stream<Integer> stream = Stream.iterate(0, n -> n + 2).limit(5);
stream.collect(Collectors.toList()).forEach(System.out::println);
Stream<Double> stream = Stream.generate(Math::random).limit(5);
stream.collect(Collectors.toList()).forEach(System.out::println);
  • limit
List<Student> l = student.getStudentlist();
l.stream().
        filter(student1 -> (17 == student1.getAge())).
        forEach(System.out::println);

System.out.println("\n=======limit=======\n");
//limit
l.stream().
        filter(student1 -> (17 == student1.getAge())).
        limit(3).
        forEach(System.out::println);
  • map

List<Student> list = student.getStudentlist();
list.stream().
        //map(x->x.getClassname().length()).
        mapToDouble(x -> x.getName().length()).
        forEach(System.out::println);
Stream.of("a-b-c-d","e-f-i-g-h")
        .flatMap(e->Stream.of(e.split("-")))
        .forEach(System.out::println);
  • max_min
Stream.of(0, 9, 8, 4, 5, 6, -1)
        .max(Integer::compareTo)
        .ifPresent(System.out::print);
        
System.out.println("\n\n===ifPresent()=====\n");
list.stream()
        .min(Comparator.comparing(x -> x.getAge()))
        .ifPresent(System.out::print);

System.out.println("\n\n===get()=====\n");
Student u = list.stream()
        .max(Comparator.comparing(x -> x.getAge()))
        .get();
System.out.println(u.toString());
  • peek

List<Student> list = s.getStudentlist();
list.stream()
        .peek(x->x.setName(x.getClassname()+x.getAge()))
        .forEach(System.out::println);
  • skip
List<Student> list = student.getStudentlist();
list.stream()
        .filter(x -> x.getAge() > 16)
        .forEach(System.out::println);
System.out.println("\n=======   skip  ======\n");
list.stream()
        .filter(x -> x.getAge() > 16)
        .skip(2)
        .forEach(System.out::println);
  • sort

list.stream()
        .sorted(Comparator.comparing(Student::getAge))
        .forEach(System.out::println);
list.stream()
        .sorted(
        //(x1, x2) -> x1.getAge() > x2.getAge() ? 1 : x1.getAge() == x2.getAge() ? 0 : -1
        (x1, x2) -> Integer.compare(x1.getAge(), x2.getAge())
        ).forEach(System.out::println);

Stream结束状态

  • collection

Integer[] arr = {
     1, 2, 3, 4, 5, 6, 7, 8, 9};
List l = Arrays.stream(arr)
        .filter(x -> x % 2 == 0)
        .collect(Collectors.toList());
for (int i = 0; i < l.size(); i++) {
     
    System.out.println(l.get(i));
}
  • count
List<Student> list = student.getStudentlist();
//注意 返回的是 long 类型
long i = list.stream().count();
System.out.println(i);
  • findFirst_Any
List<Student> l = s.getStudentlist();
l.stream().findFirst().ifPresent(System.out::print);
System.out.println("\n===================\n");

l.stream().findAny().ifPresent(System.out::print);
//加入parallel后,结果可能会和findFirst不一样,并且每次结果可能都不一样
l.stream().parallel().findAny().ifPresent(System.out::print);
  • foreach
Employ employ = new Employ();
List<Employ> list = employ.getEmploylist();
list.stream().map(Employ::getAddr).
        collect(Collectors.toList()).
        //forEach(b-> System.out.println(b));
        forEach(System.out::println);
  • matchAll_Any_None
Student student = new Student();
List<Student> list = student.getStudentlist();
//注意 返回的是 long 类型
list.stream().forEach(System.out::println);
System.out.println("=============\n");
//16存在,则返回false,26不存在,则返回true
boolean t = list.stream().noneMatch(x -> x.getAge() == 16);
boolean t1 = list.stream().noneMatch(x -> x.getAge() == 26);
System.out.println(t);
System.out.println(t1);

//全部都含有班这个字
boolean t = list.stream().allMatch(x -> x.getClassname().contains("班"));
System.out.println(t);

//只要有一个含有 李四4
boolean t = list.stream().anyMatch(x -> x.getName().equals("李四4"));
System.out.println(t);
  • reduce

int ageSum = list.stream()
        .map(x -> x.getAge())
        .reduce(0, (x1, x2) -> x1 + x2);
System.out.println(ageSum);

Stream的各种集合转换

  • Array2Stream2List

Integer[] arr = {
     1, 2, 3, 4, 5, 6, 7, 8, 9};
List<Integer> l = Arrays.stream(arr).filter(x -> x % 2 == 0).
        collect(Collectors.toList());
for (int i : l) {
     
    System.out.println(i);
}
  • Value2Stream
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
stream.distinct().forEach(ii -> {
     
    System.out.println(ii);
});
  • File2Stream
String path = "data.txt";
Stream<String> lines =
        Files.lines(Paths.get(path), Charset.defaultCharset());
List l = lines.collect(Collectors.toList());
for (int i = 0; i < l.size(); i++) {
     
    System.out.println(l.get(i));
}
  • List2Map

Employ employ = new Employ();
List<Employ> list = employ.getEmploylist();
Map<String, Double> map = list.stream().collect(Collectors.toMap(Employ::getName, Employ::getSalary));

for (String i : map.keySet()) {
     
    System.out.println("key:   " + i + "     value:  " + map.get(i));
}
  • List2Stream
Employ employ = new Employ();
List<Employ> list = employ.getEmploylist();
  • Stream2Array

Object[] array = Stream.of(1, 3, 4, 6, 94, 3, 90, 5, 77, 6, 54, 3).toArray();
for (int i = 0; i < array.length; i++) {
     
    System.out.println(array[i]);
}

你可能感兴趣的:(高并发,高可用,高性能专题,stream,java,lambda,并发编程)