@Beforepublic void init() { random = new Random(); stuList = new ArrayList<Student>() { { for (int i = 0; i < 100; i++) { add(new Student("student" + i, random.nextInt(50) + 50)); } } };} public class Student { private String name; private Integer score; //-----getters and setters-----} //1列出班上超過85分的學生姓名,并按照分數(shù)降序輸出用戶名字@Testpublic void test1() { List<String> studentList = stuList.stream() .filter(x->x.getScore()>85) .sorted(Comparator.comparing(Student::getScore).reversed()) .map(Student::getName) .collect(Collectors.toList()); System.out.println(studentList);}
@Testpublic void test1(){ Stream<String> stream = Stream.generate(()->"user").limit(20); stream.forEach(System.out::println); stream.forEach(System.out::println);}
public boolean filter(Student s) { System.out.println("begin compare"); return s.getScore() > 85;} @Testpublic void test() { Stream<Student> stream = Stream.of(stuArr).filter(this::filter); System.out.println("split-------------------------------------"); List<Student> studentList = stream.collect(toList());}
List<String> wordList; @Beforepublic void init() { wordList = new ArrayList<String>() { { add("a"); add("b"); add("c"); add("d"); add("e"); add("f"); add("g"); } };}/** * 延遲執(zhí)行特性,在聚合操作之前都可以添加相應元素 */@Testpublic void test() { Stream<String> words = wordList.stream(); wordList.add("END"); long n = words.distinct().count(); System.out.println(n);}
/** * 通過數(shù)組創(chuàng)建流 */@Testpublic void testArrayStream(){ //1.通過Arrays.stream //1.1基本類型 int[] arr = new int[]{1,2,34,5}; IntStream intStream = Arrays.stream(arr); //1.2引用類型 Student[] studentArr = new Student[]{new Student("s1",29),new Student("s2",27)}; Stream<Student> studentStream = Arrays.stream(studentArr); //2.通過Stream.of Stream<Integer> stream1 = Stream.of(1,2,34,5,65); //注意生成的是int[]的流 Stream<int[]> stream2 = Stream.of(arr,arr); stream2.forEach(System.out::println);}
@Testpublic void testEmptyStream(){ //創(chuàng)建一個空的stream Stream<Integer> stream = Stream.empty();}
@Testpublic void testUnlimitStream(){ //創(chuàng)建無限流,通過limit提取指定大小 Stream.generate(()->"number"+new Random().nextInt()).limit(100).forEach(System.out::println); Stream.generate(()->new Student("name",10)).limit(20).forEach(System.out::println);}
/** * 產生規(guī)律的數(shù)據 */@Testpublic void testUnlimitStream1(){ Stream.iterate(0,x->x+1).limit(10).forEach(System.out::println); Stream.iterate(0,x->x).limit(10).forEach(System.out::println); //Stream.iterate(0,x->x).limit(10).forEach(System.out::println);與如下代碼意思是一樣的 Stream.iterate(0, UnaryOperator.identity()).limit(10).forEach(System.out::println);}
@Testpublic void testFilter(){ Integer[] arr = new Integer[]{1,2,3,4,5,6,7,8,9,10}; Arrays.stream(arr).filter(x->x>3&&x<8).forEach(System.out::println);}
/** * flapMap:拆解流 */@Testpublic void testFlapMap1() { String[] arr1 = {"a", "b", "c", "d"}; String[] arr2 = {"e", "f", "c", "d"}; String[] arr3 = {"h", "j", "c", "d"}; // Stream.of(arr1, arr2, arr3).flatMap(x -> Arrays.stream(x)).forEach(System.out::println); Stream.of(arr1, arr2, arr3).flatMap(Arrays::stream).forEach(System.out::println);}
String[] arr1 = {"abc","a","bc","abcd"};/** * Comparator.comparing是一個鍵提取的功能 * 以下兩個語句表示相同意義 */@Testpublic void testSorted1_(){ /** * 按照字符長度排序 */ Arrays.stream(arr1).sorted((x,y)->{ if (x.length()>y.length()) return 1; else if (x.length()<y.length()) return -1; else return 0; }).forEach(System.out::println); Arrays.stream(arr1).sorted(Comparator.comparing(String::length)).forEach(System.out::println);} /** * 倒序 * reversed(),java8泛型推導的問題,所以如果comparing里面是非方法引用的lambda表達式就沒辦法直接使用reversed() * Comparator.reverseOrder():也是用于翻轉順序,用于比較對象(Stream里面的類型必須是可比較的) * Comparator. naturalOrder():返回一個自然排序比較器,用于比較對象(Stream里面的類型必須是可比較的) */@Testpublic void testSorted2_(){ Arrays.stream(arr1).sorted(Comparator.comparing(String::length).reversed()).forEach(System.out::println); Arrays.stream(arr1).sorted(Comparator.reverseOrder()).forEach(System.out::println); Arrays.stream(arr1).sorted(Comparator.naturalOrder()).forEach(System.out::println);} /** * thenComparing * 先按照首字母排序 * 之后按照String的長度排序 */@Testpublic void testSorted3_(){ Arrays.stream(arr1).sorted(Comparator.comparing(this::com1).thenComparing(String::length)).forEach(System.out::println);}public char com1(String x){ return x.charAt(0);}
@Before public void init(){ arr1 = new String[]{"a","b","c","d"}; arr2 = new String[]{"d","e","f","g"}; arr3 = new String[]{"i","j","k","l"}; } /** * limit,限制從流中獲得前n個數(shù)據 */ @Test public void testLimit(){ Stream.iterate(1,x->x+2).limit(10).forEach(System.out::println); } /** * skip,跳過前n個數(shù)據 */ @Test public void testSkip(){// Stream.of(arr1).skip(2).limit(2).forEach(System.out::println); Stream.iterate(1,x->x+2).skip(1).limit(5).forEach(System.out::println); } /** * 可以把兩個stream合并成一個stream(合并的stream類型必須相同) * 只能兩兩合并 */ @Test public void testConcat(){ Stream<String> stream1 = Stream.of(arr1); Stream<String> stream2 = Stream.of(arr2); Stream.concat(stream1,stream2).distinct().forEach(System.out::println); }
@Beforepublic void init(){ arr = new String[]{"b","ab","abc","abcd","abcde"};} /** * max、min * 最大最小值 */@Testpublic void testMaxAndMin(){ Stream.of(arr).max(Comparator.comparing(String::length)).ifPresent(System.out::println); Stream.of(arr).min(Comparator.comparing(String::length)).ifPresent(System.out::println);} /** * count * 計算數(shù)量 */@Testpublic void testCount(){ long count = Stream.of(arr).count(); System.out.println(count);} /** * findFirst * 查找第一個 */@Testpublic void testFindFirst(){ String str = Stream.of(arr).parallel().filter(x->x.length()>3).findFirst().orElse("noghing"); System.out.println(str);} /** * findAny * 找到所有匹配的元素 * 對并行流十分有效 * 只要在任何片段發(fā)現(xiàn)了第一個匹配元素就會結束整個運算 */@Testpublic void testFindAny(){ Optional<String> optional = Stream.of(arr).parallel().filter(x->x.length()>3).findAny(); optional.ifPresent(System.out::println);} /** * anyMatch * 是否含有匹配元素 */@Testpublic void testAnyMatch(){ Boolean aBoolean = Stream.of(arr).anyMatch(x->x.startsWith("a")); System.out.println(aBoolean);} @Testpublic void testStream1() { Optional<Integer> optional = Stream.of(1,2,3).filter(x->x>1).reduce((x,y)->x+y); System.out.println(optional.get());}
@Testpublic void testOptional2() { Integer[] arr = new Integer[]{4,5,6,7,8,9}; Integer result = Stream.of(arr).filter(x->x>9).max(Comparator.naturalOrder()).orElse(-1); System.out.println(result); Integer result1 = Stream.of(arr).filter(x->x>9).max(Comparator.naturalOrder()).orElseGet(()->-1); System.out.println(result1); Integer result2 = Stream.of(arr).filter(x->x>9).max(Comparator.naturalOrder()).orElseThrow(RuntimeException::new); System.out.println(result2);}
@Testpublic void testStream1() { Optional<Student> studentOptional = Optional.of(new Student("user1",21)); Optional<String> optionalStr = studentOptional.map(Student::getName); System.out.println(optionalStr.get());} public static Optional<Double> inverse(Double x) { return x == 0 ? Optional.empty() : Optional.of(1 / x);} public static Optional<Double> squareRoot(Double x) { return x < 0 ? Optional.empty() : Optional.of(Math.sqrt(x));} /** * Optional的迭代 */@Testpublic void testStream2() { double x = 4d; Optional<Double> result1 = inverse(x).flatMap(StreamTest7::squareRoot); result1.ifPresent(System.out::println); Optional<Double> result2 = Optional.of(4.0).flatMap(StreamTest7::inverse).flatMap(StreamTest7::squareRoot); result2.ifPresent(System.out::println);}
Student[] students;@Beforepublic void init(){ students = new Student[100]; for (int i=0;i<30;i++){ Student student = new Student("user",i); students[i] = student; } for (int i=30;i<60;i++){ Student student = new Student("user"+i,i); students[i] = student; } for (int i=60;i<100;i++){ Student student = new Student("user"+i,i); students[i] = student; } }@Testpublic void testCollect1(){ /** * 生成List */ List<Student> list = Arrays.stream(students).collect(toList()); list.forEach((x)-> System.out.println(x)); /** * 生成Set */ Set<Student> set = Arrays.stream(students).collect(toSet()); set.forEach((x)-> System.out.println(x)); /** * 如果包含相同的key,則需要提供第三個參數(shù),否則報錯 */ Map<String,Integer> map = Arrays.stream(students).collect(toMap(Student::getName,Student::getScore,(s,a)->s+a)); map.forEach((x,y)-> System.out.println(x+"->"+y));} /** * 生成數(shù)組 */@Testpublic void testCollect2(){ Student[] s = Arrays.stream(students).toArray(Student[]::new); for (int i=0;i<s.length;i++) System.out.println(s[i]);} /** * 指定生成的類型 */@Testpublic void testCollect3(){ HashSet<Student> s = Arrays.stream(students).collect(toCollection(HashSet::new)); s.forEach(System.out::println);} /** * 統(tǒng)計 */@Testpublic void testCollect4(){ IntSummaryStatistics summaryStatistics = Arrays.stream(students).collect(Collectors.summarizingInt(Student::getScore)); System.out.println("getAverage->"+summaryStatistics.getAverage()); System.out.println("getMax->"+summaryStatistics.getMax()); System.out.println("getMin->"+summaryStatistics.getMin()); System.out.println("getCount->"+summaryStatistics.getCount()); System.out.println("getSum->"+summaryStatistics.getSum());}
Student[] students;@Beforepublic void init(){ students = new Student[100]; for (int i=0;i<30;i++){ Student student = new Student("user1",i); students[i] = student; } for (int i=30;i<60;i++){ Student student = new Student("user2",i); students[i] = student; } for (int i=60;i<100;i++){ Student student = new Student("user3",i); students[i] = student; } }@Testpublic void testGroupBy1(){ Map<String,List<Student>> map = Arrays.stream(students).collect(groupingBy(Student::getName)); map.forEach((x,y)-> System.out.println(x+"->"+y));} /** * 如果只有兩類,使用partitioningBy會比groupingBy更有效率 */@Testpublic void testPartitioningBy(){ Map<Boolean,List<Student>> map = Arrays.stream(students).collect(partitioningBy(x->x.getScore()>50)); map.forEach((x,y)-> System.out.println(x+"->"+y));} /** * downstream指定類型 */@Testpublic void testGroupBy2(){ Map<String,Set<Student>> map = Arrays.stream(students).collect(groupingBy(Student::getName,toSet())); map.forEach((x,y)-> System.out.println(x+"->"+y));} /** * downstream 聚合操作 */@Testpublic void testGroupBy3(){ /** * counting */ Map<String,Long> map1 = Arrays.stream(students).collect(groupingBy(Student::getName,counting())); map1.forEach((x,y)-> System.out.println(x+"->"+y)); /** * summingInt */ Map<String,Integer> map2 = Arrays.stream(students).collect(groupingBy(Student::getName,summingInt(Student::getScore))); map2.forEach((x,y)-> System.out.println(x+"->"+y)); /** * maxBy */ Map<String,Optional<Student>> map3 = Arrays.stream(students).collect(groupingBy(Student::getName,maxBy(Comparator.comparing(Student::getScore)))); map3.forEach((x,y)-> System.out.println(x+"->"+y)); /** * mapping */ Map<String,Set<Integer>> map4 = Arrays.stream(students).collect(groupingBy(Student::getName,mapping(Student::getScore,toSet()))); map4.forEach((x,y)-> System.out.println(x+"->"+y));}
DoubleStream doubleStream; IntStream intStream; /** * 原始類型流的初始化 */ @Before public void testStream1(){ doubleStream = DoubleStream.of(0.1,0.2,0.3,0.8); intStream = IntStream.of(1,3,5,7,9); IntStream stream1 = IntStream.rangeClosed(0,100); IntStream stream2 = IntStream.range(0,100); } /** * 流與原始類型流的轉換 */ @Test public void testStream2(){ Stream<Double> stream = doubleStream.boxed(); doubleStream = stream.mapToDouble(Double::new); }
public void peek1(int x) { System.out.println(Thread.currentThread().getName() + ":->peek1->" + x); } public void peek2(int x) { System.out.println(Thread.currentThread().getName() + ":->peek2->" + x); } public void peek3(int x) { System.out.println(Thread.currentThread().getName() + ":->final result->" + x); } /** * peek,監(jiān)控方法 * 串行流和并行流的執(zhí)行順序 */ @org.junit.Test public void testPeek() { Stream<Integer> stream = Stream.iterate(1, x -> x + 1).limit(10); stream.peek(this::peek1).filter(x -> x > 5) .peek(this::peek2).filter(x -> x < 8) .peek(this::peek3) .forEach(System.out::println); } @Test public void testPeekPal() { Stream<Integer> stream = Stream.iterate(1, x -> x + 1).limit(10).parallel(); stream.peek(this::peek1).filter(x -> x > 5) .peek(this::peek2).filter(x -> x < 8) .peek(this::peek3) .forEach(System.out::println); }
/** * 生成一億條0-100之間的記錄 */@Beforepublic void init() { Random random = new Random(); list = Stream.generate(() -> random.nextInt(100)).limit(100000000).collect(toList());} /** * tip */@org.junit.Testpublic void test1() { long begin1 = System.currentTimeMillis(); list.stream().filter(x->(x > 10)).filter(x->x<80).count(); long end1 = System.currentTimeMillis(); System.out.println(end1-begin1); list.stream().parallel().filter(x->(x > 10)).filter(x->x<80).count(); long end2 = System.currentTimeMillis(); System.out.println(end2-end1); long begin1_ = System.currentTimeMillis(); list.stream().filter(x->(x > 10)).filter(x->x<80).distinct().sorted().count(); long end1_ = System.currentTimeMillis(); System.out.println(end1-begin1); list.stream().parallel().filter(x->(x > 10)).filter(x->x<80).distinct().sorted().count(); long end2_ = System.currentTimeMillis(); System.out.println(end2_-end1_); }
val count = sc.parallelize(1 to NUM_SAMPLES).filter { _ => val x = math.random val y = math.random x*x + y*y < 1}.count()println(s"Pi is roughly ${4.0 * count / NUM_SAMPLES}")