JDK8-StreamAPI(六)

筛选切片

package cn.wcj.jdk8.lambda.test;



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

import org.junit.Test;
/*
 * 一、Stream API 的操作步骤:
 * 
 * 1. 创建 Stream
 * 
 * 2. 中间操作
 * 
 * 3. 终止操作(终端操作)
 */
public class StreamTest01 {

    @Test
    public void test1() {
        //1. Collection 提供了两个方法  stream() 与 parallelStream()
        List list=new ArrayList<>()   ;
        Stream stream=list.stream()   ;   //顺序流
        Stream parallelStream = list.parallelStream();   //并行流

        //2. 通过 Arrays 中的 stream() 获取一个数组流
        Integer[] nums=new Integer[10]    ;
        Stream stream2 = Arrays.stream(nums)   ;


        //3. 通过 Stream 类中静态方法 of()
        Stream stream3 = Stream.of(1,2,3,4,5,6)  ;

        //4.创建无限流
        Stream stream4 = Stream.iterate(0, (x)->x+2).limit(10);
        stream4.forEach(System.out::println) ;

        Stream<Double> stream5 = Stream.generate(Math::random).limit(10) ;
        stream5.forEach(System.out::println)  ;


    }

    List<Emp> emps=new ArrayList<Emp>(
            Arrays.asList(
               new Emp("3333", "张三", 3333.33, 31),          
               new Emp("4444", "李四", 4444.44, 41),          
               new Emp("5555", "王五", 5555.55, 51),          
               new Emp("6666", "赵六", 6666.66, 61),          
               new Emp("7777", "田七", 7777.77, 71),  
               new Emp("7777", "田七", 7777.77, 71),  
               new Emp("7777", "田七", 7777.77, 71),  
               new Emp("7777", "田七", 7777.77, 71),  
               new Emp("7777", "田七", 7777.77, 71),  
               new Emp("7777", "田七", 7777.77, 71)
            )
        );


    /*
      筛选与切片
        filter——接收 Lambda , 从流中排除某些元素。
        limit——截断流,使其元素不超过给定数量。
        skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
        distinct——筛选,通过流所生成元素的 hashCode()equals() 去除重复元素
     */
    //内部迭代:迭代操作 Stream API 内部完成
    @Test
    public void test2(){
        //所有的中间操作不会做任何的处理
        Stream<Emp> stream = emps.stream()
                                 .filter((e)->{
                                                System.out.println("中间操作") ;
                                                return e.getAge()>35  ;
                                              })  ;
        //只有当做终止操作时,所有的中间操作会一次性的全部执行,称为“惰性求值”
        stream.forEach(System.out::println)  ;    
    }

    //外部迭代
    @Test
    public void test3(){
        Iterator<Emp> iterator = emps.iterator();
        while(iterator.hasNext())
            System.out.println(iterator.next())  ;
    }



    @Test
    public void test4(){
        emps.stream()
            .filter((e)->{
                System.out.println("短路") ; //类似&& ||
                return e.getSalary()>5000   ;
            })
            .limit(2)
            .forEach(System.out::println)  ;
    }

    @Test
    public void test5(){
        emps.stream()
            .filter((e)->{
                System.out.println("短路")  ;
                return e.getSalary()>5000   ;
            })
            .skip(2)  
            .forEach(System.out::println);
    }

    @Test
    public void test6(){
        emps.stream()
            .distinct()
            .forEach(System.out::println) ;
    }



}

映射、排序

package cn.wcj.jdk8.lambda.test;

import java.util.ArrayList;

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

import org.junit.Test;

import cn.wcj.jdk8.lambda.test.Emp.Status;
/**
 * 
* 

Title:StreamTest02

*

Description: StreamAPI

*

Company:Software College

* @author SuccessKey(WangCJ) * @date 2017619日 下午9:05:49 */ public class StreamTest02 { List emps=new ArrayList( Arrays.asList( new Emp("3333", "张三", 3333.33, 31,Status.BUSY), new Emp("4444", "李四", 4444.44, 41,Status.FREE), new Emp("5555", "王五", 5555.55, 51,Status.VOCATION), new Emp("6666", "赵六", 6666.66, 71,Status.BUSY), new Emp("7777", "田七", 7777.77, 71,Status.FREE), new Emp("7777", "田八", 7777.77, 71,Status.FREE), new Emp("7777", "田九", 7777.77, 71,Status.BUSY) ) ); //2. 中间操作 /* 映射 map——接收 Lambda , 将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。 flatMap——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流 */ public static Stream filterCharacter(String str){ char[] charArray = str.toCharArray(); List list=new ArrayList<>() ; for (Character chr : charArray) { list.add(chr) ; } return list.stream() ; } @Test public void test1() { emps.stream() .map(Emp::getEname) .forEach(System.out::println) ; System.out.println("-----------------------") ; List strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee"); strList.stream() .map(String::toUpperCase) .forEach(System.out::println) ; System.out.println("-----------------------") ; Stream> stream=strList.stream() .map(StreamTest02::filterCharacter); stream.forEach((sm)->{ sm.forEach(System.out::println); }); System.out.println("-----------------------") ; strList.stream() .flatMap(StreamTest02::filterCharacter) .forEach(System.out::println); } @Test public void test2(){ List<String> strList = new ArrayList<>(); strList.add("aaa") ; strList.add("bbb") ; strList.add("ccc") ; strList.add("ddd") ; strList.add("eee") ; List strList2 = new ArrayList<>(); strList2.add("fff") ; strList2.addAll(strList) ; // strList2.add(strList) ; System.out.println(strList2); } /* sorted()——自然排序 sorted(Comparator com)——定制排序 */ @Test public void test4(){ emps.stream() .map(Emp::getEname) .sorted() .forEach(System.out::println) ; System.out.println("--------------------") ; emps.stream() .sorted((e1,e2)->{ if(e1.getAge()==e2.getAge()) return e1.getEname().compareTo(e2.getEname()); else return Integer.compare(e1.getAge(), e2.getAge()) ; }) .forEach(System.out::println) ; } /* allMatch——检查是否匹配所有元素 anyMatch——检查是否至少匹配一个元素 noneMatch——检查是否没有匹配的元素 findFirst——返回第一个元素 findAny——返回当前流中的任意元素 count——返回流中元素的总个数 max——返回流中最大值 min——返回流中最小值 */ @Test public void test5(){ boolean allMatch = emps.stream() .allMatch((e)->e.getStatus().equals(Status.FREE)); System.out.println(allMatch); boolean anyMatch = emps.stream() .anyMatch((e)->e.getStatus().equals(Status.FREE)) ; System.out.println(anyMatch) ; boolean noneMatch = emps.stream() .noneMatch((e)->e.getStatus().equals(Status.FREE)) ; System.out.println(noneMatch) ; } @Test public void test6(){ Optional<Emp> first = emps.stream() .sorted((e1,e2)->Double.compare(e1.getSalary(), e2.getSalary())) .findFirst(); System.out.println(first.get()) ; System.out.println("---------------------"); Optional<Emp> findAny = emps.parallelStream() .filter((e)->e.getStatus().equals(Status.FREE)) .findAny(); System.out.println(findAny.get()); } @Test public void test7(){ long count = emps.stream() .filter((e)->e.getStatus().equals(Status.FREE)) .count(); System.out.println(count); Optional<Double> max = emps.stream() .map(Emp::getSalary) .max(Double::compare) ; System.out.println(max.get()) ; Optional<Emp> min = emps.stream() .min((e1,e2)->Double.compare(e1.getSalary(), e2.getSalary())); System.out.println(min.get()); } }

规约收集

package cn.wcj.jdk8.lambda.test;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
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.stream.Collectors;

import org.junit.Test;

import cn.wcj.jdk8.lambda.test.Emp.Status;
/**
 * 
* 

Title:StreamTest

*

Description: Stream归约与收集

*

Company:Software College

* @author SuccessKey(WangCJ) * @date 2017620日 下午3:20:08 */ public class StreamTest { List emps=new ArrayList( Arrays.asList( new Emp("3333", "张三", 3333.33, 31,Status.BUSY), new Emp("4444", "李四", 4444.44, 41,Status.FREE), new Emp("5555", "王五", 5555.55, 51,Status.VOCATION), new Emp("6666", "赵六", 6666.66, 71,Status.BUSY), new Emp("7777", "田七", 7777.77, 71,Status.FREE), new Emp("7777", "田七", 7777.77, 71,Status.FREE), new Emp("7777", "田七", 7777.77, 71,Status.BUSY) ) ); @Test public void test1() { List 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<Double> sum2 = emps.stream() .map(Emp::getSalary) .reduce(Double::sum) ; System.out.println(sum2.get()) ; } //统计“六”出现次数 @Test public void test2(){ Optional<Integer> reduce = emps.stream() .map(Emp::getEname) .flatMap(StreamTest02::filterCharacter) .map((chr)->{ if(chr.equals('六')) return 1 ; else return 0 ; }) .reduce(Integer::sum) ; System.out.println(reduce.get()) ; } //collect——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法 @Test public void test3(){ List<String> list = emps.stream() .map(Emp::getEname) .collect(Collectors.toList()) ; list.stream() .forEach(System.out::println); System.out.println("----------------------------------") ; Set<String> set = emps.stream() .map(Emp::getEname) .collect(Collectors.toSet()) ; set.stream() .forEach(System.out::println) ; System.out.println("----------------------------------") ; HashSet<String> hashSet = emps.stream() .map(Emp::getEname) .collect(Collectors.toCollection(HashSet::new)) ; hashSet.stream() .forEach(System.out::println); } @Test public void test4(){ Optional<Double> collect = emps.stream() .map(Emp::getSalary) .collect(Collectors.maxBy(Double::compare)) ; System.out.println(collect.get()) ; System.out.println("---------------------------") ; Optional<Emp> collect2 = emps.stream() .collect(Collectors.minBy((e1,e2) -> Double.compare(e1.getSalary(), e2.getSalary()))); System.out.println(collect2.get()); System.out.println("---------------------------") ; Double sum = emps.stream() .collect(Collectors.summingDouble(Emp::getSalary)) ; System.out.println(sum) ; System.out.println("---------------------------") ; Double avg = emps.stream() .collect(Collectors.averagingDouble(Emp::getSalary)) ; System.out.println(avg) ; System.out.println("---------------------------") ; Long count = emps.stream() .collect(Collectors.counting()) ; System.out.println(count) ; DoubleSummaryStatistics summaryStatistics = emps.stream() .collect(Collectors.summarizingDouble(Emp::getSalary)) ; System.out.println(summaryStatistics.getMax()) ; } //分组 @Test public void test5(){ Map<Status, List<Emp>> collect = emps.stream() .collect(Collectors.groupingBy(Emp::getStatus)); System.out.println(collect) ; } @Test public void test6(){ Map<Status, Map<String, List<Emp>>> map = emps.stream() .collect(Collectors.groupingBy(Emp::getStatus, Collectors.groupingBy((e)->{ if(e.getAge()>60) return "老年" ; else if(e.getAge()>35) return "中年" ; else return "成年" ; }))) ; System.out.println(map); } //分区 @Test public void test7(){ Map<Boolean, List<Emp>> collect = emps.stream() .collect(Collectors.partitioningBy((e)->e.getSalary() >= 5000)); System.out.println(collect); } @Test public void test8(){ String string = emps.stream() .map(Emp::getEname) .collect(Collectors.joining(",")); System.out.println(string); String string2 = emps.stream() .map(Emp::getEmpno) .collect(Collectors.joining(",", "工号:(", ")")) ; System.out.println(string2); } @Test public void test9(){ Optional<Double> collect = emps.stream() .map(Emp::getSalary) .collect(Collectors.reducing(Double::sum)) ; System.out.println(collect.get()) ; } }

StreamAPI练习

package cn.wcj.jdk8.lambda.exam  ;

import static org.junit.Assert.*;

import org.junit.Test;

public class Trader {

    private String name;
    private String city;

    public Trader() {
    }

    public Trader(String name, String city) {
        this.name = name;
        this.city = city;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "Trader [name=" + name + ", city=" + city + "]";
    }



}
package cn.wcj.jdk8.lambda.exam;
public class Transaction {

    private Trader trader;
    private int year;
    private int value;

    public Transaction() {
    }

    public Transaction(Trader trader, int year, int value) {
        this.trader = trader;
        this.year = year;
        this.value = value;
    }

    public Trader getTrader() {
        return trader;
    }

    public void setTrader(Trader trader) {
        this.trader = trader;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Transaction [trader=" + trader + ", year=" + year + ", value="
                + value + "]";
    }

}
package cn.wcj.jdk8.lambda.exam;



import java.util.ArrayList;
import java.util.Arrays;
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.junit.Before;
import org.junit.Test;

public class StreamTest {

    List transactions = null;

    @Before
    public void before(){
        //交易员
        Trader raoul = new Trader("Raoul", "Cambridge");
        Trader mario = new Trader("Mario", "Milan");
        Trader alan = new Trader("Alan", "Cambridge");
        Trader brian = new Trader("Brian", "Cambridge");

        //交易
        transactions = Arrays.asList(
                new Transaction(brian, 2011, 300),
                new Transaction(raoul, 2012, 1000),
                new Transaction(raoul, 2011, 400),
                new Transaction(mario, 2012, 710),
                new Transaction(mario, 2012, 700),
                new Transaction(alan, 2012, 950)
        );
    }


    //1. 找出2011年发生的所有交易, 并按交易额排序(从低到高)
    @Test
    public void test1() {
        transactions.stream()
                     .filter((t)->t.getYear()==2011)
                     .sorted((x,y)->Integer.compare(x.getValue(), y.getValue()))
                     .forEach(System.out::println);
    }


    //2. 交易员都在哪些不同的城市工作过?
    @Test
    public void test2(){
        transactions.stream()
                    .map(t->t.getTrader().getCity())
                    .distinct()
                    .forEach(System.out::println) ;
    }

    //3. 查找所有来自剑桥的交易员,并按姓名排序
    @Test
    public void test3(){
        transactions.stream()
                    .filter(t->"Cambridge".equals(t.getTrader().getCity()))
                    .sorted((t1,t2)->t1.getTrader().getName().compareTo(t2.getTrader().getName()))
                    .forEach(System.out::println);;
    }

    //4. 返回所有交易员的姓名字符串,按字母顺序排序
    @Test
    public void test4(){
         transactions.stream()
                     .map((t)->t.getTrader().getName())
                     .distinct()
                     .sorted()
                     .forEach(System.out::println)   ;
         System.out.println("--------------------")  ;
         String names = transactions.stream()
                     .map((t)->t.getTrader().getName())
                     .distinct()
                     .sorted()
                     .collect(Collectors.joining(",")) ;
         System.out.println(names)  ;
         System.out.println("--------------------")  ;
         String reduce = transactions.stream()
                     .map((t)->t.getTrader().getName())
                     .sorted()
                     .reduce("",String::concat)   ;
         System.out.println(reduce);
         System.out.println("--------------------")  ;
         transactions.stream()
                     .map((t)->t.getTrader().getName())
                     .distinct()
                     .flatMap(StreamTest::filterCharacter)
                     .sorted(String::compareToIgnoreCase)
                     .forEach(System.out::print)  ;
    }

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

    //5. 有没有交易员是在米兰工作的?
    @Test
    public void test5(){
         boolean match = transactions.stream()
                     .anyMatch((t)->"Milan".equals(t.getTrader().getCity()));
         System.out.println(match?"有":"没有");
    }

    //6. 打印生活在剑桥的交易员的所有交易额
    @Test
    public void test6(){
        transactions.stream()
                    .filter((t)->"Cambridge".equals(t.getTrader().getCity()))
                    .map(Transaction::getValue)
                    .forEach(System.out::println) ;
    }

    //7. 所有交易中,最高的交易额是多少
    @Test
    public void test7(){
        DoubleSummaryStatistics collect = transactions.stream()
                    .collect(Collectors.summarizingDouble(Transaction::getValue));
        System.out.println(collect.getMax());
    }

    //8. 找到交易额最小的交易
    @Test
    public void test8(){
        Optional<Integer> min = transactions.stream()
                    .map(Transaction::getValue)
                    .min((v1,v2) -> Integer.compare(v1, v2)) ;
        System.out.println(min.get());
    }



}

你可能感兴趣的:(Java高级编程)