#增強for迴圈 增強for迴圈 (也稱for each迴圈) 是迭代器遍歷方法的一個“簡化版”,是JDK1.5以後出來的一個高級for迴圈,專門用來遍曆數組和集合。 普通for迴圈 int[] num = {1,2,3,4,5,6}; for(int i = 0 ; i<num.length ; ...
今天對這些內容進行了一個複習,以寫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的提示自動轉換
這隻是一個語法糖,能看懂代碼就行,不要過於糾結