本文主要介紹Java8 中Arrays.sort()及Collections.sort()中Lambda表達(dá)式及增強(qiáng)版Comparator的使用。
作者:石頭成說(shuō)
來(lái)源:CSDN
原文:https://blog.csdn.net/qq_27127145/article/details/83930498
版權(quán)聲明:本文為博主原創(chuàng)文章顽爹,轉(zhuǎn)載請(qǐng)附上博文鏈接!
import com.google.common.collect.Lists;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ComparatorTest {
@Test
public void test1(){
/**
* Collections.sort()使用
*/
//被排序的集合
List<User> userList = Lists.newArrayList(new User("Jack",11),new User("Jack",10));
//1. Java8之前跃惫,使用匿名內(nèi)部類的基本排序
Collections.sort(userList, new Comparator<User>() {
@Override
public int compare(User user1, User user2) {
return user1.getAge().compareTo(user2.getAge());
}
});
//2. Java8,使用Lambda表達(dá)式的基本排序
Collections.sort(userList,
(User user1, User user2) ->user1.getAge().compareTo(user2.getAge()));
//userList.sort((User user1, User user2) -> user1.getAge().compareTo(user2.getAge()));
//3. Java8,Lambda表達(dá)式可以簡(jiǎn)化庄呈,省略定義類型User
userList.sort((user1, user2) -> user1.getAge().compareTo(user2.getAge()));
//4. Java8,Lambda表達(dá)式鸯乃,多條件排序
userList.sort((user1, user2) -> {
if (user1.getName().equals(user2.getName())) {
return user1.getAge() - user2.getAge();
} else {
return user1.getName().compareTo(user2.getName());
}
});
//5. Java8,多條件組合排序
userList.sort(Comparator.comparing(User::getName).thenComparing(User::getAge));
//6. Java8,提取Comparator進(jìn)行排序
Collections.sort(userList, Comparator.comparing(User::getName));
//7. Java8,自定義靜態(tài)的比較方法來(lái)排序(靜態(tài)方法必須寫在被比較的類(這里是User類)中)
userList.sort(User::compareByAgeThenName);
//8. Java8,反轉(zhuǎn)排序
Comparator<User> comparator = (user1, user2) -> user1.getName().compareTo(user2.getName());
userList.sort(comparator);//先按name排序
userList.sort(comparator.reversed());//反轉(zhuǎn)排序
Assert.assertEquals(userList.get(0),new User("Jack",10));
/**
* Arrays.sort()使用
*/
//被排序的字符串?dāng)?shù)組
String[] months = {"January","February","March","April","May","June","July","August","September","October","December"};
//按字符串長(zhǎng)度排序
//1.
Arrays.sort(months, (a, b) -> Integer.signum(a.length() - b.length()));
//2.
Arrays.sort(months, Comparator.comparingInt(String::length));
//3.
Arrays.sort(months, (a, b) -> a.length() - b.length());
//4.
Arrays.sort(months,
(String a, String b) -> { return Integer.signum(a.length() - b.length()); }
);
System.out.println(Arrays.toString(months));
}
}