前言
Lambda表达式中Comparator和对集合(Collection)进行排序
数据结构准备
public class Item {
private Long id;
private String name;
private Double score;
private BigDecimal bigDecimal;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
public BigDecimal getBigDecimal() {
return bigDecimal;
}
public void setBigDecimal(BigDecimal bigDecimal) {
this.bigDecimal = bigDecimal;
}
}
/**
* init List
* @return
*/
private List<Item> initList(){
List<Item> itemList = new ArrayList<>();
for (int i=0;i<10;i++){
Item item = new Item();
item.setId((long) i);
item.setName("Test"+i);
item.setScore(Math.random());
item.setBigDecimal(new BigDecimal(Math.random()));
itemList.add(item);
}
return itemList;
}
不使用Lambda表达式的基本排序
public void noLambdaSort(){
List<Item> itemList = initList();
Collections.shuffle(itemList);
Collections.sort(itemList, new Comparator<Item>() {
@Override
public int compare(Item o1, Item o2) {
return o1.getName().compareTo(o2.getName());
}
});
}
使用Lambda表达式的排序
public void lambdaSort(){
List<Item> itemList = initList();
Collections.shuffle(itemList);
itemList.sort((Item item1,Item item2)->item1.getName().compareTo(item2.getName()));
itemList.sort(( item1, item2)->item1.getName().compareTo(item2.getName()));
itemList.sort(Comparator.comparing(Item::getName));
Collections.sort(itemList, Comparator.comparing(Item::getName));
Collections.sort(itemList, (o1, o2) -> o1.getName().compareTo(o2.getName()));
}
反转排序
public void lambdaReversedSort(){
List<Item> itemList = initList();
Collections.shuffle(itemList);
Comparator<Item> comparator = Comparator.comparing(Item::getName);
itemList.sort(comparator.reversed());
}
多条件组合排序
public void multipleConditionsSort(){
List<Item> itemList = initList();
Collections.shuffle(itemList);
itemList.sort(Comparator.comparing(Item::getName).thenComparingDouble(Item::getScore));
}
网友评论