我們今天來討論比較器 & 集合的用法
List<String> sampleStrings =
Arrays.asList("this", "is", "a", "list", "of", "strings");
Collections.sort(sampleStrings);
System.out.println(sampleStrings);
List<String> result = sampleStrings.stream()
.sorted()
.collect(Collectors.toList());
System.out.println(result);
//output:
//[a, is, list, of, strings, this]
//[a, is, list, of, strings, this]
//Lambda expression
List<String> result = sampleStrings.stream()
.sorted((s1, s2) -> s1.length() - s2.length())
.collect(toList());
//Comparator.comparingInt static method reference
List<String> result = sampleStrings.stream()
.sorted(Comparator.comparingInt(String::length))
.collect(toList());
//using Comparator static method
sampleStrings.stream()
.sorted(Comparator.comparing(String::length)
.thenComparing(Comparator.naturalOrder()))
.collect(toList());
此為串流聚合操作,利用 Collectors.toList, toSet, toCollection 的靜態方法
這我們之前常用,就不多舉例了
List<String> superHeroes =
Stream.of("Mr. Furious", "The Blue Raja", "The Shoveler",
"The Bowler", "Invisible Boy", "The Spleen", "The Sphinx")
.collect(Collectors.toList());
我們想要把一個線性集合加入到 Map,key 是使用物件的其中一個特性,可以使用 Collectors.toMap,具體例子如下:
class Book {
private int id;
private String name;
private double price;
}
List<Book> books = Arrays.asList(
new Book(1, "Modern Java Recipes", 49.99),
new Book(2, "Java 8 in Action", 49.99),
new Book(3, "Java SE8 for the Really Impatient", 39.99),
new Book(4, "Functional Programming in Java", 27.64),
new Book(5, "Making Java Groovy", 45.99)
new Book(6, "Gradle Recipes for Android", 23.76)
);
Map<Integer, Book> bookMap = books.stream()
.collect(Collectors.toMap(Book::getId, b -> b));
//or
Map<Integer, Book> bookMap = books.stream()
.collect(Collectors.toMap(Book::getId, Function.identity()));
System.out.println(bookMap);
現代 Java - 輕鬆解決 Java 8 與 9 的難題(O'REILLY)