給定一個類。在Java中使用流暢的鏈接排序集合8
public class Entity {
private Long id;
private String prodName;
private BigDecimal price;
// Constructors + getters + setters + hashcode() + equals() + toString().
}
構建一個列表Entity
。
List<Entity> list = new ArrayList<>();
Entity entity = new Entity();
entity.setId(1L);
entity.setProdName("A");
entity.setPrice(new BigDecimal(10));
list.add(entity);
entity = new Entity();
entity.setId(2L);
entity.setProdName("B");
entity.setPrice(new BigDecimal(20));
list.add(entity);
entity = new Entity();
entity.setId(3L);
entity.setProdName("C");
entity.setPrice(new BigDecimal(30));
list.add(entity);
entity = new Entity();
entity.setId(4L);
entity.setProdName("D");
entity.setPrice(new BigDecimal(40));
list.add(entity);
entity = new Entity();
entity.setId(5L);
entity.setProdName("E");
entity.setPrice(new BigDecimal(50));
list.add(entity);
entity = new Entity();
entity.setId(6L);
entity.setProdName("F");
entity.setPrice(new BigDecimal(60));
list.add(entity);
entity = new Entity();
entity.setId(7L);
entity.setProdName("F");
entity.setPrice(new BigDecimal(60));
list.add(entity);
試圖名單由price
和prodName
降序通過id
進行排序,然後按升序排列。
Comparator<Entity> comparator = Comparator.comparing(Entity::getPrice).reversed();
comparator = comparator.thenComparing(Entity::getProdName).reversed();
comparator = comparator.thenComparingLong(Entity::getId);
list = list.stream().sorted(comparator).collect(Collectors.toList());
// Or Collections.sort(list, comparator);
list.stream().forEachOrdered(l -> System.out.println(l.getId() + " : " + l.getPrice() + " : " + l.getProdName()));
執行排序後,列表應該如下所示。
6 : 60 : F
7 : 60 : F
5 : 50 : E
4 : 40 : D
3 : 30 : C
2 : 20 : B
1 : 10 : A
不過這個名單,進行整理後,顯示如下。
1 : 10 : A
2 : 20 : B
3 : 30 : C
4 : 40 : D
5 : 50 : E
6 : 60 : F
7 : 60 : F
排序後的列表是不根據給定的準則(由id
由price
和prodName
和升序降序)。
還需要做些什麼?
嘗試根據本文提供的示例嘗試一些代碼:http://www.leveluplunch.com/java/tutorials/007-sort-arraylist-stream-of -objects-in-java8/ –
'comparator.thenComparingLong(Entity :: getId).reversed()'? – marstran
[這裏](http://stackoverflow.com/questions/14154127/collections-sortlistt-comparator-super-t-method-example)是用於收集排序使用比較一個很好的例子。 – mystery