I have an input array as
["Setra","Mercedes","Volvo","Mercedes","Skoda","Iveco","MAN",null,"Skoda","Iveco"]
expected output should be
{Iveco=2, Mercedes=2, Skoda=2, MAN=1, Setra=1, Volvo=1}
meaning a map with the key as Vehicle brands and the value as their occurrence count and the similar valued elements should be sorted by the keys alphabetically and value.
I have tried like
public static String busRanking(List<String> busModels) {
Map<String, Long> counters = busModels.stream().skip(1).filter(Objects::nonNull)
.filter(bus -> !bus.startsWith("V"))
.collect(Collectors.groupingBy(bus-> bus, Collectors.counting()));
Map<String, Long> finalMap = new LinkedHashMap<>();
counters.entrySet().stream()
.sorted(Map.Entry.comparingByValue(
Comparator.reverseOrder()))
.forEachOrdered(
e -> finalMap.put(e.getKey(),
e.getValue()));
return finalMap.toString();
}
public static void main(String[] args) {
List<String> busModels = Arrays.asList( "Setra","Mercedes","Volvo","Mercedes","Skoda","Iveco","MAN",null,"Skoda","Iveco");
String busRanking = busRanking(busModels);
System.out.println(busRanking);
}
And the output I am getting
{Skoda=2, Mercedes=2, Iveco=2, Setra=1, MAN=1}
Any suggestion? And the output has to be obtained using single stream()