Created
November 25, 2021 20:04
-
-
Save ericfialkowski/8b3f59f71d0759121b274bfb30e35388 to your computer and use it in GitHub Desktop.
Custom Map Entry Comparator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.ericski; | |
import java.util.Arrays; | |
import java.util.Collections; | |
import java.util.Comparator; | |
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.stream.Collectors; | |
public class App | |
{ | |
public static class EntryComparator implements Comparator<Map.Entry<Integer,Integer>> { | |
@Override | |
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) { | |
int cv = Integer.compare(o1.getValue(),o2.getValue()); | |
if (cv == 0) { | |
return Integer.compare(o1.getKey(), o2.getKey()); | |
} | |
return cv; | |
} | |
} | |
public static void process(int[] input) { | |
var counts = new HashMap<Integer, Integer>(); | |
Arrays.stream(input).forEach(i -> counts.put(i,counts.getOrDefault(i,0) + 1)); | |
var l2 = counts.entrySet().stream().sorted(new EntryComparator()).collect(Collectors.toList()); | |
Collections.reverse(l2); | |
System.out.println(" Original Map: " + counts); | |
System.out.println("Sorted Values: " + l2); | |
} | |
public static void main( String[] args ) | |
{ | |
process(new int[]{1,2,3,4,5,1,2,3,1,2,3,1,2,5,5,5}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment