1. Get the most frequent element in a list - java 8
Tools:
-JDK 8-CoderPad/Sanbox
Solution:
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.function.Function;
/*
* To execute Java, please define "static void main" on a class
* named Solution.
*
* If you need more classes, simply define them inline.
*/
class Solution
{
public static void main(String[] args)
{
//Init list
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(1);
list.add(3);
list.add(2);
list.add(1);
int most=mostFrequentElement(list);
//Print result
System.out.print("The most frequent element in list is:"+most);
}
//Method that return the most frequent element in array
public static int mostFrequentElement(List<Integer> list)
{
//Group the list in a map by the number of appareance
Map<Integer,Long> group = list
.stream()
.collect
(
Collectors
.groupingBy
(
Function.identity()
,Collectors.counting()
)
)
;
Map<Integer, Long> finalMap = new LinkedHashMap<>();
//This method does not mutate the original map.
//Put in first place the element which have more appearances than the others one based on the previous group
group
.entrySet()
.stream()
.sorted
(
Map
.Entry
.<Integer,Long>comparingByValue()
.reversed()
)
.forEachOrdered(e -> finalMap.put(e.getKey(),e.getValue()));
return finalMap.entrySet().stream().findFirst().get().getKey();
}
}
import java.util.*;
import java.util.stream.Collectors;
import java.util.function.Function;
/*
* To execute Java, please define "static void main" on a class
* named Solution.
*
* If you need more classes, simply define them inline.
*/
class Solution
{
public static void main(String[] args)
{
//Init list
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(1);
list.add(3);
list.add(2);
list.add(1);
int most=mostFrequentElement(list);
//Print result
System.out.print("The most frequent element in list is:"+most);
}
//Method that return the most frequent element in array
public static int mostFrequentElement(List<Integer> list)
{
//Group the list in a map by the number of appareance
Map<Integer,Long> group = list
.stream()
.collect
(
Collectors
.groupingBy
(
Function.identity()
,Collectors.counting()
)
)
;
Map<Integer, Long> finalMap = new LinkedHashMap<>();
//This method does not mutate the original map.
//Put in first place the element which have more appearances than the others one based on the previous group
group
.entrySet()
.stream()
.sorted
(
Map
.Entry
.<Integer,Long>comparingByValue()
.reversed()
)
.forEachOrdered(e -> finalMap.put(e.getKey(),e.getValue()));
return finalMap.entrySet().stream().findFirst().get().getKey();
}
}
No hay comentarios:
Publicar un comentario