Group By, Count and Sort
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
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
}
sorting
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Java8Example2 {
public static void main(String[] args) {
//3 apple, 2 banana, others 1
List 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
Group by Price – Collectors.groupingBy and Collectors.mapping example.
import java.math.BigDecimal; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; public class Java8Examples4 { public static void main(String[] args) { //3 apple, 2 banana, others 1 List- 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")) ); //group by price Map<bigdecimal, list<Item>> groupByPriceMap = items.stream().collect(Collectors.groupingBy(Item::getPrice)); System.out.println(groupByPriceMap); // group by price, uses 'mapping' to convert List
- to Set Map<bigdecimal, set<string>> result = items.stream().collect( Collectors.groupingBy(Item::getPrice, Collectors.mapping(Item::getName, Collectors.toSet()) ) ); System.out.println(result); } }