今天對這些內容進行了一個復習,以寫demo加做筆記的形式
stream能夠更加優雅的處理集合、陣列等資料,讓我們寫出更加直觀、可讀性更高的資料處理代碼
創建steam流的方式
set、list能夠直接通過.stream()的形式創建steam流
而陣列需要通過 Arrays.stream(arr); Stream.of(arr);
map需要通過entrySet()方法,先將map轉換成Set<Map.Entry<String, Integer>> set物件,再通過set.stream()的方式轉換
stream中的api比較多
/**
* @author Pzi
* @create 2022-12-30 13:22
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class Test2 {
@Test
public void test1() {
List<Author> authors = S.getAuthors();
authors
.stream()
.distinct()
.filter(author -> {
// 滿足這個條件,那么才會被篩選到繼續留在stream中
return author.getAge() < 18;
})
.forEach(author -> System.out.println(author.getAge()));
}
// 對雙列集合map的stream操作
@Test
public void test2() {
Map<String, Integer> map = new HashMap<>();
map.put("蠟筆小新", 19);
map.put("黑子", 17);
map.put("日向翔陽", 16);
//entrySet是一個包含多個Entry的Set資料結構,Entry是key-val型的資料結構
Set<Map.Entry<String, Integer>> entries = map.entrySet();
entries.stream()
.filter(entry -> {
return entry.getValue() > 17;
})
.forEach(entry -> {
System.out.println(entry);
});
}
// stream的map操作,提取stream中物件的屬性,或者計算
@Test
public void test3() {
List<Author> authors = S.getAuthors();
authors
.stream()
.map(author -> author.getName())
.forEach(name -> System.out.println(name));
System.out.println(1);
authors
.stream()
.map(author -> author.getAge())
.map(age -> age + 10)
.forEach(age -> System.out.println(age));
}
// steam的sorted操作
@Test
public void test4() {
List<Author> authors = S.getAuthors();
authors
.stream()
.distinct()
.sorted(((o1, o2) -> o2.getAge() - o1.getAge()))
.skip(1)
.forEach(author -> System.out.println(author.getName() + " " + author.getAge()));
}
// flapMap的使用,重新組裝,改變stream流中存放的物件
@Test
public void test5() {
// 列印所有書籍的名字,要求對重復的元素進行去重,
List<Author> authors = S.getAuthors();
authors.stream()
.flatMap(author -> author.getBooks().stream())
.distinct()
.forEach(book -> System.out.println(book.getName()));
authors.stream()
// 將以authors為物件的stream流 組裝成 以book為物件的strem流
.flatMap(author -> author.getBooks().stream())
.distinct()
// 將每個book中的category轉換成陣列,然后將[x1,x2]代表分類的陣列轉換成stream流,然后使用flapMap將該陣列stream流組裝成以x1,x2...為物件的stream流
// 將以book為物件的strem流 組裝成 以category為物件的stream流
.flatMap(book -> Arrays.stream(book.getCategory().split(",")))
.distinct()
.forEach(category -> System.out.println(category));
}
// 陣列轉換成stream流
@Test
public void test6() {
Integer[] arr = {1, 2, 3, 4, 5};
Stream<Integer> stream = Arrays.stream(arr);
stream
.filter(integer -> integer > 3)
.forEach(integer -> System.out.println(integer));
}
@Test
public void test7() {
// 列印這些作家的所出書籍的數目,注意洗掉重復元素,
List<Author> authors = S.getAuthors();
long count = authors
.stream()
.flatMap(author -> author.getBooks().stream())
.distinct()
.count();
System.out.println(count);
}
// max() min()
@Test
public void test8() {
// 分別獲取這些作家的所出書籍的最高分和最低分并列印,
List<Author> authors = S.getAuthors();
Optional<Integer> max = authors.stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getScore())
.max((score1, score2) -> score1 - score2);
Optional<Integer> min = authors.stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getScore())
.min((score1, score2) -> score1 - score2);
System.out.println(max.get());
System.out.println(min.get());
}
// stream 的 collect()
@Test
public void test9() {
// 獲取所有作者名字
List<Author> authors = S.getAuthors();
Set<String> collect = authors.stream()
.map(author -> author.getName())
.collect(Collectors.toSet());
System.out.println(collect);
//獲取一個所有書名的Set集合,
Set<String> collect1 = authors.stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getName())
.collect(Collectors.toSet());
System.out.println(collect1);
// 獲取一個Map集合,map的key為作者名,value為List<Book>
Map<String, List<Book>> collect2 = authors.stream()
.distinct()
.collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
System.out.println(collect2);
}
// anyMatch
@Test
public void test10() {
List<Author> authors = S.getAuthors();
boolean b = authors.stream()
.anyMatch(author -> author.getAge() > 29);
System.out.println(b);
}
// allMatch
@Test
public void test11() {
List<Author> authors = S.getAuthors();
boolean b = authors.stream()
.allMatch(author -> author.getAge() > 18);
System.out.println(b);
}
// findFirst
@Test
public void test12() {
List<Author> authors = S.getAuthors();
Optional<Author> first = authors.stream()
.sorted(((o1, o2) -> o1.getAge() - o2.getAge()))
.findFirst();
first.ifPresent(author -> System.out.println(author));
}
// reduce() 的使用
@Test
public void test13() {
// 使用reduce求所有作者年齡的和
List<Author> authors = S.getAuthors();
Integer sum = authors.stream()
.distinct()
.map(author -> author.getAge())
.reduce(0, (result, element) -> result + element);
// .reduce(0, (result, element) -> result + element);
System.out.println(sum);
}
@Test
public void test14() {
// 使用reduce求所有作者中年齡的最小值
List<Author> authors = S.getAuthors();
Integer minAge = authors.stream()
.map(author -> author.getAge())
.reduce(Integer.MAX_VALUE, (res, ele) -> res > ele ? ele : res);
System.out.println(minAge);
}
// 沒有初始值的reduce()使用
@Test
public void test15() {
List<Author> authors = S.getAuthors();
Optional<Integer> age = authors.stream()
.map(author -> author.getAge())
.reduce((res, ele) -> res > ele ? ele : res);
System.out.println(age.get());
}
// Optional物件的封裝,orElseGet的使用
@Test
public void test16() {
Optional<Author> authorOptional = Optional.ofNullable(null);
Author author1 = authorOptional.orElseGet(() -> new Author(1l, "1", 1, "1", null));
System.out.println(author1);
// authorOptional.ifPresent(author -> System.out.println(author.getName()));
}
@Test
public void test17() {
Optional<Author> authorOptional = Optional.ofNullable(null);
try {
Author author = authorOptional.orElseThrow((Supplier<Throwable>) () -> new RuntimeException("exception"));
System.out.println(author.getName());
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
// Optional的filter()方法
// ifPresent()可以安全消費Optional中包裝的物件
@Test
public void test18() {
Optional<Author> optionalAuthor = Optional.ofNullable(S.getAuthors().get(0));
optionalAuthor
.filter(author -> author.getAge() > 14)
.ifPresent(author -> System.out.println(author));
}
// Optional的isPresent()方法,用來判斷該Optional是否包裝了物件
@Test
public void test19() {
Optional<Author> optionalAuthor = Optional.ofNullable(S.getAuthors().get(0));
boolean present = optionalAuthor.isPresent();
if (present) {
System.out.println(optionalAuthor.get().getName());
}
}
// Optional的map(),將一個 Optional 轉換成另一個 Optional
@Test
public void test20() {
Optional<Author> optionalAuthor = Optional.ofNullable(S.getAuthors().get(0));
optionalAuthor.ifPresent(author -> System.out.println(author.getBooks()));
Optional<List<Book>> books = optionalAuthor.map(author -> author.getBooks());
books.ifPresent(books1 -> System.out.println(books.get()));
}
// 類的靜態方法
@Test
public void test21() {
List<Author> authors = S.getAuthors();
authors.stream()
.map(author -> author.getAge())
.map(integer -> String.valueOf(integer));
// lambda方法體中只有一行代碼
// .map(String::valueOf);
}
// 物件的實體方法
@Test
public void test22() {
List<Author> authors = S.getAuthors();
Stream<Author> authorStream = authors.stream();
StringBuilder sb = new StringBuilder();
authorStream.map(author -> author.getName())
// lambda方法體中只有一行代碼,且將引數全部按照順序傳入這個重寫方法中
.forEach(str -> sb.append(str));
}
// 介面中只有一個抽象方法稱為函式式介面
// 方法參考的條件是:lambda方法體中只有一行方法
// 構造器的方法參考
@Test
public void test23() {
List<Author> authors = S.getAuthors();
authors.stream()
.map(Author::getName)
.map(StringBuilder::new)
.map(stringBuilder -> stringBuilder.append("abc"))
.forEach(System.out::println);
}
// steam提供的處理基本資料型別,避免頻繁的自動拆/裝箱,從而達到省時,提高性能
@Test
public void test24() {
List<Author> authors = S.getAuthors();
authors.stream()
.map(author -> author.getAge())
.map(age -> age + 10)
.filter(age -> age > 18)
.map(age -> age + 2)
.forEach(System.out::println);
authors.stream()
.mapToInt(author -> author.getAge())
.map(age -> age + 10)
.filter(age -> age > 18)
.map(age -> age + 2)
.forEach(System.out::println);
}
@Test
public void test25() {
List<Author> authors = S.getAuthors();
authors.stream()
.parallel()
.map(author -> author.getAge())
.peek(integer -> System.out.println(integer+" "+Thread.currentThread().getName()))
.reduce(new BinaryOperator<Integer>() {
@Override
public Integer apply(Integer result, Integer ele) {
return result + ele;
}
}).ifPresent(sum -> System.out.println(sum));
}
}
lambda運算式
lambda運算式只關心 形參串列 和 方法體
用在重寫抽象方法的時候,一般都是采用lambda運算式的方式來重寫
函式式介面
函式式介面:介面中只有一個抽象方法,就稱之為函式式介面,在Java中Consumer,Funciton,Supplier
方法參考
方法參考:當lambda運算式的方法體中只有一行代碼,并且符合一些規則,就可以將該行代碼轉換成方法參考的形式
可以直接使用idea的提示自動轉換
這只是一個語法糖,能看懂代碼就行,不要過于糾結
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/540984.html
標籤:其他
上一篇:增強for回圈
