1. 程式人生 > 實用技巧 >java8的Stream常用方法測試

java8的Stream常用方法測試

列舉一些實際開發中會用到的Stream方法,

首先,建立實體類:

package testStream;

/**
 * Created by XuYinShan on 2020/7/20
 */
public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return
name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person{" + "name='"
+ name + '\'' + ", age=" + age + '}'; } }

接下來是測試Stream的方法類TestStream:

package testStream;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import 
static java.util.stream.Collectors.*; /** * 測試java8 Stream * * Created by XuYinShan on 2020/7/20 */ public class TestStream { // 測試mapToInt()及sum()方法 @Test public void testStream1() { String[] strarr = {"abc", "defg", "hijk"}; // 1.mapToInt()的引數是流中的每個元素,可以對每個元素進行操作,生成新的流 // 2.流呼叫sum方法累加流中的元素 int length = Arrays.stream(strarr).mapToInt(s -> s.length()).sum(); System.out.println("長度和: " + length); // 測試結果: 長度和: 11 } // 測試filter方法 @Test public void testStream2() { // 獲取年齡為20的person物件的list List<Person> list = new ArrayList<>(); list.add(new Person("xx", 20)); list.add(new Person("xys", 25)); list.add(new Person("xqe", 19)); // 1.filter方法中的person也是代指流中的每個元素,通過表示式實現過濾 // 2.使用collect(toList())將流轉成集合 List listNew = list.stream().filter(p -> p.getAge() == 20).collect(toList()); System.out.println(listNew); // 測試結果: [Person{name='xx', age=20}] } // 測試sorted()方法 @Test public void testStream3() { // person根據年齡排序 List<Person> list = new ArrayList<>(); list.add(new Person("xx", 20)); list.add(new Person("xys", 25)); list.add(new Person("xqe", 19)); // sorted()實現排序 // 1.a的方式是方便理解的,降序是(p1, p2) -> p2.getAge() - p1.getAge() // 2.b方式如果需要降序排列,在Comparator.comparingInt(Person::getAge)後面加上reversed() // a. // List listNew = list.stream().sorted((p1, p2) -> p1.getAge() - p2.getAge()).collect(toList()); // b. List listNew = list.stream().sorted(Comparator.comparingInt(Person::getAge)).collect(toList()); System.out.println(listNew); // 測試結果: [Person{name='xqe', age=19}, Person{name='xx', age=20}, Person{name='xys', age=25}] } // 測試limit()方法 @Test public void testStream4() { // 獲取指定person物件個數 List<Person> list = new ArrayList<>(); list.add(new Person("xx", 20)); list.add(new Person("xys", 25)); list.add(new Person("xqe", 19)); List listNew = list.stream().limit(2).collect(toList()); System.out.println(listNew); // 測試結果: [Person{name='xx', age=20}, Person{name='xys', age=25}] } // 測試skip()方法 @Test public void testStream5() { // 去除前n個元素 List<Person> list = new ArrayList<>(); list.add(new Person("xx", 20)); list.add(new Person("xys", 25)); list.add(new Person("xqe", 19)); List listNew = list.stream().skip(2).collect(toList()); System.out.println(listNew); // 測試結果: [Person{name='xqe', age=19}] } // 測試map()方法 @Test public void testStream6() { // 將物件的姓名存為list List<Person> list = new ArrayList<>(); list.add(new Person("xx", 20)); list.add(new Person("xys", 25)); list.add(new Person("xqe", 19)); List listNew = list.stream().map(Person::getName).collect(toList()); // List listNew = list.stream().map(p->p.getName()).collect(toList()); System.out.println(listNew); // 測試結果: [xx, xys, xqe] } // 測試flatMap()方法 @Test public void testStream7() { // flatMap將流合併 List<String> list = new ArrayList<>(); list.add("aaa bbb ccc"); list.add("ddd eee fff"); list.add("ggg hhh iii"); // 先將集合中的每一項轉成陣列,然後將這些數組合併成流,最後轉成集合 list = list.stream().map(s -> s.split(" ")).flatMap(Arrays::stream).collect(toList()); System.out.println(list); // 測試結果: [aaa, bbb, ccc, ddd, eee, fff, ggg, hhh, iii] } // 測試anyMatch()方法 @Test public void testStream8() { // 是否存在符合條件的物件 List<Person> list = new ArrayList<>(); list.add(new Person("xx", 20)); list.add(new Person("xys", 25)); list.add(new Person("xqe", 17)); // 測試流中的是否有符合條件的元素,引數是斷言型別函式 boolean b = list.stream().anyMatch(person -> person.getAge() == 30); System.out.println(b); // 測試結果: false } // 測試reduce()方法 @Test public void testStream9() { // 運算 map 將流中的每一個元素 T 對映為 R(類似型別轉換) List<Person> list = new ArrayList<>(); list.add(new Person("xx", 23)); list.add(new Person("xys", 25)); list.add(new Person("xqe", 18)); // 1 求和 // Integer reduce = list.stream().map(Person::getAge).reduce(0, (a, b) -> a + b); Integer reduce = list.stream().map(Person::getAge).reduce(0, (a, b) -> a + b); // 2 求和 // int reduce = list.stream().map(Person::getAge).reduce(0, Integer::sum); // Optional<Integer> reduce = list.stream().map(Person::getAge).reduce(Integer::sum); // 3 乘積 // int reduce = list.stream().map(Person::getAge).reduce(1, (a, b) -> a * b); // 返回流中個數 // long count = list.stream().count(); // list.stream().forEach(System.out::println); System.out.println(reduce); } // 測試max(),min(),average()方法 @Test public void testStream10() { // 數值流相關 List<Person> list = new ArrayList<>(); list.add(new Person("xx", 20)); list.add(new Person("xys", 25)); list.add(new Person("xqe", 19)); // 最大 OptionalInt max = list.stream().mapToInt(Person::getAge).max(); // 最小 OptionalInt min = list.stream().mapToInt(Person::getAge).min(); // 求和(推薦) int sum = list.stream().mapToInt(Person::getAge).sum(); // 平均值 OptionalDouble average = list.stream().mapToInt(Person::getAge).average(); // Stream 求和 IntStream intStream = IntStream.rangeClosed(1, 10); // 閉區間 IntStream intStream2 = IntStream.range(1, 10); // 左閉右開 System.out.println(intStream2.sum()); } // 測試陣列轉流 @Test public void testStream11() { // 將陣列轉成數值流,同時取下標從1開始到3(不含3)結束的流 int[] a = {1, 2, 3, 4}; Arrays.stream(a, 1, 3).forEach(System.out::println); // 測試結果: 2 3 } // 檔案生成流 @Test public void testStream12() throws IOException { // 按行讀取d盤下的aa.txt Stream<String> lines = Files.lines(Paths.get("D:\\aa.txt")); // 輸出 // lines.flatMap(line -> Arrays.stream(line.split(" "))).distinct().forEach(System.out::println); // list存放讀取到的檔案流 List<String> collect = lines.flatMap(line -> Arrays.stream(line.split(" "))).distinct().collect(toList()); System.out.println(collect); } // 測試iterate()方法 @Test public void testStream13() { // 函式生成流,生成10個奇數 Stream.iterate(0, n -> n + 1).filter(x -> x % 2 != 0) .limit(10).forEach(System.out::println); // 測試結果: 1 3 5 7 9 11 13 15 17 19 } // 測試toMap()方法 @Test public void testStream14() { // collect() 把流中所有元素收集到一個 List, Set 或 Collection 中 List<Person> list = new ArrayList<>(); list.add(new Person("xx", 20)); list.add(new Person("xys", 25)); list.add(new Person("xqe", 19)); Map<String, Person> map = list.stream().collect(toMap(Person::getName, p -> p)); System.out.println(map); // 測試結果: {xx=Person{name='xx', age=20}, xys=Person{name='xys', age=25}, xqe=Person{name='xqe', age=19}} } // 取最值 @Test public void testStream15() { List<Person> list = new ArrayList<>(); list.add(new Person("xx", 20)); list.add(new Person("xys", 25)); list.add(new Person("xqe", 19)); // 1 Optional<Person> collect = list.stream().collect(maxBy(Comparator.comparing(Person::getAge))); // 2 Optional<Person> max = list.stream().max(Comparator.comparing(Person::getAge)); System.out.println(max); } // 連線字串 @Test public void testStream16() { List<Person> list = new ArrayList<>(); list.add(new Person("xx", 20)); list.add(new Person("xys", 25)); list.add(new Person("xqe", 19)); String collect = list.stream().map(Person::getName).collect(joining()); String collect2 = list.stream().map(Person::getName).collect(joining(",")); // 三個引數依次為:連線符,字首,字尾 String collect3 = list.stream().map(Person::getName).collect(joining(" and ", "Today ", " play games.")); System.out.println(collect3); } // 分組 @Test public void testStream17() { List<Person> list = new ArrayList<>(); list.add(new Person("xuxiang", 20)); list.add(new Person("xuyinshan", 25)); list.add(new Person("xuyinzhe", 25)); Map<Integer, List<Person>> collect = list.stream().collect(groupingBy(Person::getAge)); System.out.println(collect); // 測試結果: {20=[Person{name='xuxiang', age=20}], 25=[Person{name='xuyinshan', age=25}, Person{name='xuyinzhe', age=25}]} } // 分割槽 partitioningBy() @Test public void testStream18() { List<Person> list = new ArrayList<>(); list.add(new Person("xuxiang", 20)); list.add(new Person("xuyinshan", 25)); list.add(new Person("xuyinzhe", 20)); Map<Boolean, List<Person>> map = list.stream() .collect(partitioningBy(p -> p.getAge() <= 20)); System.out.println(map); // 測試結果: {false=[Person{name='xuyinshan', age=25}], true=[Person{name='xuxiang', age=20}, Person{name='xuyinzhe', age=20}]} } // 並行 parallel() 實現累加 @Test public void testStream19() { int i = Stream.iterate(1, a -> a + 1).limit(100).parallel().reduce(0, Integer::sum); System.out.println(i); // 測試結果: 5050 } }

詳細api可參考:https://www.matools.com/api/java8中的java.util.stream;