1、使用Stream 方法排序集合
Listing 6-10. SortByLengthThenNaturalReversed.java
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class SortByLengthThenNaturalReversed {
public static void main(String []args) {
List words = Arrays.asList("follow your heart but take your brain with you".split(" "));
Comparator<String> lengthCompare = (str1, str2) -> str1.length() - str2.length();
words.stream()
.distinct()
.sorted(lengthCompare.thenComparing(String::compareTo).reversed())
.forEach(System.out::println);
}
}
This program prints:
follow
heart
brain
your
with
take
you
but
2、保存集合对象--保存一个集合通过使用集合方法和类
Listing 6-12. CollectorsToSet.java
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
public class CollectorsToSet {
public static void main(String []args) {
String []roseQuote = "a rose is a rose is a rose".split(" ");
Set words = Arrays.stream(roseQuote).collect(Collectors.toSet());
words.forEach(System.out::println);
}
}
This program prints:
a
rose
is
除了Set还有Map,List,TreeSet等集合的返回类型。