1. Group By, Count and Sort
1.1 Group by a List and display the total count of it.(按列表分组,并显示其总数)
public class Java8Example1 {
public static void main(String[] args) {
//3 apple, 2 banana, others 1
List<String> items =
Arrays.asList("apple", "apple", "banana",
"apple", "orange", "banana", "papaya");
Map<String, Long> result =
items.stream().collect(
Collectors.groupingBy(
Function.identity(), Collectors.counting()
)
);
System.out.println(result);
}
}
output
{
papaya=1, orange=1, banana=2, apple=3
}
1.2 Add sorting.(增加排序实现)
public class Java8Example2 {
public static void main(String[] args) {
//3 apple, 2 banana, others 1
List<String> items =
Arrays.asList("apple", "apple", "banana",
"apple", "orange", "banana", "papaya");
Map<String, Long> result =
items.stream().collect(
Collectors.groupingBy(
Function.identity(), Collectors.counting()
)
);
Map<String, Long> finalMap = new LinkedHashMap<>();
//Sort a map and add to finalMap
result.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue()
.reversed()).forEachOrdered(e -> finalMap.put(e.getKey(), e.getValue()));
System.out.println(finalMap);
}
}
output
{
apple=3, banana=2, papaya=1, orange=1
}
2. List Objects
Examples to ‘group by’ a list of user defined Objects.(通过“用户定义的对象”列表进行分组的示例。)
2.1 A Pojo.
public class Item {
private String name;
private int qty;
private BigDecimal price;
//constructors, getter/setters
}
2.2 Group by the name + Count or Sum the Qty. (name + Count分组或者 对 Qty求和分组)
public class Java8Examples3 {
public static void main(String[] args) {
//3 apple, 2 banana, others 1
List<Item> items = Arrays.asList(
new Item("apple", 10, new BigDecimal("9.99")),
new Item("banana", 20, new BigDecimal("19.99")),
new Item("orang", 10, new BigDecimal("29.99")),
new Item("watermelon", 10, new BigDecimal("29.99")),
new Item("papaya", 20, new BigDecimal("9.99")),
new Item("apple", 10, new BigDecimal("9.99")),
new Item("banana", 10, new BigDecimal("19.99")),
new Item("apple", 20, new BigDecimal("9.99"))
);
Map<String, Long> counting = items.stream().collect(
Collectors.groupingBy(Item::getName, Collectors.counting()));
System.out.println(counting);
//求和
Map<String, Integer> sum = items.stream().collect(
Collectors.groupingBy(Item::getName, Collectors.summingInt(Item::getQty)));
System.out.println(sum);
Map<String, List<Item>> env = items.stream().collect(
Collectors.groupingBy(Item::getName));
System.out.println(env);
}
}
output
//Group by + Count
{
papaya=1, banana=2, apple=3, orang=1, watermelon=1
}
//Group by + Sum qty
{
papaya=20, banana=30, apple=40, orang=10, watermelon=10
}
{
papaya=[Item(name=papaya, qty=20, price=9.99)], banana=[Item(name=banana, qty=20, price=19.99), Item(name=banana, qty=10, price=19.99)], apple=[Item(name=apple, qty=10, price=9.99), Item(name=apple, qty=10, price=9.99), Item(name=apple, qty=20, price=9.99)], orang=[Item(name=orang, qty=10, price=29.99)], watermelon=[Item(name=watermelon, qty=10, price=29.99)]}
}