java7排序和java8函数式排序区别
//java7
@Test
public void sort() {
List<Integer> list = Arrays.asList(232, 4, 25, 23, 7, 48, 9);
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer t1, Integer t2) {
return t2.compareTo(t1);
}
});
for (Integer integer : list) {
System.out.println(integer);
}
}
//java8
@Test
public void sort() {
List<Integer> list = Arrays.asList(232, 4, 25, 23, 7, 48, 9);
// list.sort(Comparator.naturalOrder());
list.sort(Comparator.reverseOrder());
list.forEach(System.out::println);
}

@Test
public void givenListOfBooks_thenExplainTheAdvantageOfFunction() {
String authorA = "张三";
String authorB = "李四";
String authorC = "王五";
String authorD = "前朝太监";
List<Book> books = Arrays.asList(
new Book("C++编程", authorA, 1216),
new Book("C#编程", authorA, 365),
new Book("Java编程", authorB, 223),
new Book("Ruby编程", authorB, 554),
new Book("21天精通Python", authorB, 607),
new Book("21天精通Go", authorC, 352),
new Book("葵花宝典", authorD, 1200),
new Book("编程圣经", authorA, 320)
);
List<Book> booksFiltered = new ArrayList<>();
for (Book book : books){
if (! "葵花宝典".equals(book.getTitle())) {
booksFiltered.add(book);
}
}
booksFiltered.sort(new Comparator<Book>() {
@Override
public int compare(Book o1, Book o2) {
return o2.getPages().compareTo(o1.getPages());
}
});
for (int i=0; i<3; i++) {
System.out.println(booksFiltered.get(i).getAuthor());
}
// 函数式
books.stream()
.filter(b -> ! "葵花宝典".equals(b.getTitle()))
.sorted((b1, b2) -> b2.getPages().compareTo(b1.getPages()))
.limit(3)
.map(Book::getAuthor)
.distinct()
.forEach(System.out::println);
}
distinct 去重