Index
- 1. Grouping elements of a List -Java 8
- 2. Sorting a map by values - Java 8
- 3. Get first element in a map
1. Grouping elements of a List -Java 8
import java.io.*;
import java.util.*;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.function.Function;
...
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(1);
list.add(3);
list.add(2);
list.add(1);
Map<Integer,Long> group = list
.stream()
.collect
(
Collectors
.groupingBy
(
Function.identity()
,Collectors.counting()
)
)
;
System.out.println(group); // out: {1=3, 2=1, 3=2}
import java.util.*;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.function.Function;
...
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(1);
list.add(3);
list.add(2);
list.add(1);
Map<Integer,Long> group = list
.stream()
.collect
(
Collectors
.groupingBy
(
Function.identity()
,Collectors.counting()
)
)
;
System.out.println(group); // out: {1=3, 2=1, 3=2}
2. Sorting a map by values - Java 8
import java.io.*;
import java.util.*;
...
Map<Integer,Long> list = new HashMap<Integer,Long>();
list.put(3,0L);
list.put(2,5L);
list.put(1,3L);
list.put(4,2L);
Map<Integer, Long> finalMap = new LinkedHashMap<>();
//This method does not mutate the original map
list
.entrySet()
.stream()
.sorted
(
Map
.Entry
.<Integer,Long>comparingByValue()
.reversed()
)
.forEachOrdered(e -> finalMap.put(e.getKey(),e.getValue()));
System.out.println(finalMap); //out: {2=5, 1=3, 4=2, 3=0}
import java.util.*;
...
Map<Integer,Long> list = new HashMap<Integer,Long>();
list.put(3,0L);
list.put(2,5L);
list.put(1,3L);
list.put(4,2L);
Map<Integer, Long> finalMap = new LinkedHashMap<>();
//This method does not mutate the original map
list
.entrySet()
.stream()
.sorted
(
Map
.Entry
.<Integer,Long>comparingByValue()
.reversed()
)
.forEachOrdered(e -> finalMap.put(e.getKey(),e.getValue()));
System.out.println(finalMap); //out: {2=5, 1=3, 4=2, 3=0}
3. Get first element in a map
import java.io.*;
import java.util.*;
...
Map<Integer,Long> map = new HashMap<Integer,Long>();
map.put(3,0L);
map.put(2,5L);
map.put(1,3L);
map.put(4,2L);
System.out.println("Key:"+map.entrySet().stream().findFirst().get().getKey()); //out: Key:1
System.out.print("Value:"+map.entrySet().stream().findFirst().get().getValue());//out: Value:3
import java.util.*;
...
Map<Integer,Long> map = new HashMap<Integer,Long>();
map.put(3,0L);
map.put(2,5L);
map.put(1,3L);
map.put(4,2L);
System.out.println("Key:"+map.entrySet().stream().findFirst().get().getKey()); //out: Key:1
System.out.print("Value:"+map.entrySet().stream().findFirst().get().getValue());//out: Value:3