JDK1.8的新特性之Stream流的使用

package com.ilike.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Stream;
import org.junit.Test;

/**
*
* @author 桑伟东
*
* Stream的三个操作步骤:
*
* 1.创建Stream
*
* 2.中间操作
*
* 3.终止操作(终端操作)
*
*
*/
public class TestStreamApi1 {

//创建Stream
@Test
public void test1(){
    //1.可以通过Collection系列集合提供的Stream()或parallelStream
    List<String> list=new ArrayList<String>();
    Stream<String> stream=  list.stream();
    //2.通过Arrays的静态方法stream获取数组流
    Student[] students=new Student[10];
    Stream<Student> stream2=Arrays.stream(students);
    //3.通过Stream中的of()静态方法也可以获取流
    Stream<String> stream3=Stream.of("aa","bb","cc");
    //4.创建无限流
    //迭代
    Stream<Integer> stream4=Stream.iterate(0, (x)->x+2);
    stream4.limit(10).forEach(System.out::println);
    //生成
    Stream.generate(()-> new Random().nextInt(100)).limit(10).forEach(System.out::println);

}

}

package com.ilike.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

import org.junit.Test;

/**
*
* @author 桑伟东
*
* Stream的三个操作步骤:
*
* 1.创建Stream
*
* 2.中间操作
*
* 3.终止操作(终端操作)
*
*
*/
public class TestStreamApi2 {

List<Student> students=Arrays.asList(
        new Student("张三", 23),
        new Student("李四", 38),
        new Student("王五", 55),
        new Student("赵六", 18),
        new Student("田七", 29),
        new Student("田七", 29),
        new Student("田七", 29));
//中间操作
/**
 * 排序
 * sorted()——自然排序(Comparable)
 * sorted(Comparator com)——定制排序(Comparator)
 */

@Test
public void test5() {
    List<String> list=Arrays.asList("aaa","bbb","ccc","ddd","eee");
    list.stream()
    .sorted()
    .forEach(System.out::println);
    System.out.println("----------------------");
    students.stream()
    .sorted((s1,s2)->{
        if(s1.getAge().equals(s2.getAge())){
            return s1.getName().compareTo(s2.getName());
        }else{
            return -s1.getAge().compareTo(s2.getAge());
        }
    })
    .forEach(System.out::println);
    }

/**
 * 映射
 * map——接受lambda ,将元素转换成其他形式或提取信息。接受一个函数作为参数,该
 *      函数会被应用到每个元素上,并将其映射成一个新的元素
 * flatMap——接受一个函数作为参数,将流中的每一个值都换成另一个流,然后把所有流连接成一个流
 */
@Test
public void test4() {
    List<String> list=Arrays.asList("aaa","bbb","ccc","ddd","eee");
    //流操作
    list.stream()
    .map((str)->str.toUpperCase())
    .forEach(System.out::println);
    System.out.println("----------------------");
    students.stream()
    .map(Student::getName)
    .forEach(System.out::println);
    System.out.println("----------------------");
    Stream<Stream<Character>> stream=list.stream()
            .map(TestStreamApi2::filterCharacter);
    stream.forEach((sm)->{
        sm.forEach(System.out::println);
    });
    System.out.println("----------------------");
    Stream<Character> stream2=  list.stream()
    .flatMap(TestStreamApi2::filterCharacter);
    stream2.forEach(System.out::println);
}



public static Stream<Character> filterCharacter(String str) {
    List<Character> list=new ArrayList<Character>();
    for (Character ch : str.toCharArray()) {
        list.add(ch);
    }
    return list.stream();
}



/**
 * 筛选与切片
 * filter——接受lambda ,从流中排除某些元素
 * limit—— 阶段流,使其不超过指定数量
 * skip(n)—— 跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流。与limit互补
 * distinct——筛选,通过硫所生成元素的hashCode()和equals去除重复元素
 * 
 */
@Test
public void test3() {
students.stream()
    .filter((s)->{
        System.out.println("短路!");
        return s.getAge()>25;
    })
    .skip(2)
    .distinct()
    .forEach(System.out::println);
}




@Test
public void test2() {
students.stream()
    .filter((s)->{
        System.out.println("短路!");
        return s.getAge()>25;
    })
    .limit(2)
    .forEach(System.out::println);
}





//内部迭代:迭代操作有Stream API完成
@Test
public void test1() {
    //1.获取流
    Stream<Student> stream=students.stream()
     //2.中间操作:不会执行任何操作
    .filter((s)->{
        System.out.println("StreamAPI的中间操作!");
        return s.getAge()>35;
    });
    //3.终止操作:一次性执行全部的内容,"即惰性求值"
    stream.forEach(System.out::println);

}

}

package com.ilike.test;

import java.util.Arrays;
import java.util.DoubleSummaryStatistics;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
import org.junit.Test;

import com.ilike.test.Student.Status;

/**
*
* @author 桑伟东
*
* 终止操作
*
*/
public class TestStreamApi3 {
List students=Arrays.asList(
new Student(“张三”, 23,5555,Status.BUSY),
new Student(“李四”, 38,6666,Status.FREE),
new Student(“王五”, 55,8888,Status.VOCATION),
new Student(“赵六”, 18,7777,Status.FREE),
new Student(“田七”, 29,9999,Status.BUSY),
new Student(“田七”, 29,9999,Status.BUSY));

/**
 * 收集
 * collect——将流转换为其他形式。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法
 */
 @Test
public void test10() {
    String str= students.stream()
             .map(Student::getName)
             .collect(Collectors.joining(","));
    System.out.println(str);

 }


 @Test
public void test9() {
DoubleSummaryStatistics dss= students.stream()
             .collect(Collectors.summarizingDouble(Student::getSalary));
System.out.println(dss.getAverage());
System.out.println(dss.getMax());
System.out.println(dss.getCount());
System.out.println(dss.getSum());


 }


//分区
 @Test
    public void test8() {
     Map<Boolean, List<Student>> map=students.stream().collect(Collectors.partitioningBy((s)-> s.getSalary()>7000));
     System.out.println(map);
 }



//多级分组
 @Test
    public void test7() {
     Map<Status, ConcurrentMap<String, List<Student>>> map= students.stream()
             .collect(Collectors.groupingBy(Student::getStatus, Collectors.groupingByConcurrent((s)->{
                 if(((Student)s).getAge()<=35){
                     return "青年";
                 }else if(((Student)s).getAge()<=50){
                     return "中年";
                 }else{
                     return "老年";
                 }
             })));
     System.out.println(map);
 }


//分组
 @Test
    public void test6() {
     Map<Status, List<Student>>  map= students.stream()
             .collect(Collectors.groupingBy(Student::getStatus));
     System.out.println(map);
 }

 @Test
    public void test5() {
     //总数
    long count=students.stream().collect(Collectors.counting());
    System.out.println(count);
     System.out.println("-------------------------------");
    //平均值
    Double avg=students.stream().collect(Collectors.averagingDouble(Student::getSalary));
    System.out.println(avg);
     System.out.println("-------------------------------");
     //总和
     Double sum= students.stream().collect(Collectors.summingDouble(Student::getSalary));
     System.out.println(sum);
     System.out.println("-------------------------------");
     //最大值
     Optional<Student> optional=students.stream()
             .collect(Collectors.maxBy((s1,s2)-> Integer.compare(s1.getSalary(), s2.getSalary())));
     System.out.println(optional.get());
     //最小值
     Optional<Integer> optional2= students.stream()
             .map(Student::getSalary)
             .collect(Collectors.minBy(Integer::compare));
     System.out.println(optional2.get());

 }



 @Test
    public void test4() {
     List<String> names= students.stream()
     .map(Student::getName)
     .collect(Collectors.toList());
     names.forEach(System.out::println);
     System.out.println("-------------------------------");
     Set<String> set= students.stream()
             .map(Student::getName)
             .collect(Collectors.toSet());
     set.forEach(System.out::println);
     System.out.println("-------------------------------");
     HashSet<String> set2= students.stream()
             .map(Student::getName)
             .collect(Collectors.toCollection(HashSet::new));
     set2.forEach(System.out::println);
 }

/**
 * 归约
 * reduce(T identity,BinaryOperator ) /reduce(BinaryOperator)——可以将流中元素反复结合起来,得到一个值
 */
 @Test
    public void test3() {
     List<Integer> list=Arrays.asList(1,2,3,4,5,6,7,8,9,10);
     Integer  sum= list.stream().reduce(0, (x,y)->x+y);
     System.out.println(sum);
     System.out.println("-------------------------------");
     Optional<Integer> optional  = students.stream().map(Student::getSalary).reduce(Integer::sum);
     System.out.println(optional.get());
 }



/**
 * 查找与匹配
 * allMatch——检查是否匹配所有元素
 * anyMatch——检查是否至少匹配一个元素
 * noneMatch——检查是否没有匹配所有元素
 * findFoirst——返回第一个元素
 * findAny——返回流中的任意元素
 * count——返回流中元素的总个数
 * max——返回流中元素的最大值
 * min——返回流中元素的最小值
 */
//统计相关
 @Test
    public void test2() {
    Long long1= students.stream().count();
    System.out.println(long1);

    Optional<Student> optional=students.stream()
            .max((s1,s2)->Integer.compare(s1.getSalary(), s2.getSalary()));
    System.out.println(optional.get());

    Optional<Integer> optional2=    students.stream()
    .map(Student::getAge)
    .min(Integer::compare);
    System.out.println(optional2.get());

 }


@Test
public void test1() {
    boolean b=  students.stream().allMatch((s)->s.getStatus().equals(Status.BUSY));
    System.out.println(b);
    System.out.println("-----------------------------------");
    boolean b2=students.stream().anyMatch((s)->s.getStatus().equals(Status.BUSY));
    System.out.println(b2);
    System.out.println("-----------------------------------");
    boolean b3=students.stream().noneMatch((s)->s.getStatus().equals(Status.BUSY));
    System.out.println(b3);
    System.out.println("-----------------------------------");
    //按工资排序,并返回第一个
    Optional<Student> opt=students.stream().sorted((s1,s2)->{
        return -s1.getSalary().compareTo(s2.getSalary());
    }).findFirst();
    System.out.println(opt.get());
    System.out.println("-----------------------------------");
    //找一个空闲的人
    Optional<Student> opt2=students.parallelStream()
     .filter((s)->s.getStatus().equals(Status.FREE))
     .findAny();
    System.out.println(opt2.get());
}

}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值