Hi all,
I got map with full duplicates (key and value are duplicated). I need to sort the map by value, it sorts, but duplicates disappear and I need to keep them. Please see my code below. Thx for any suggestion.
package learn; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; public class sortMapWithDuplicates { private static Map<Integer, String> sortByValue(Map<Integer, String> unsortMap, final boolean order) { List<Entry<Integer, String>> list = new LinkedList<>(unsortMap.entrySet()); System.out.println("check 1 - list = " + list); list.sort((o1, o2) -> order ? o1.getValue().compareTo(o2.getValue()) == 0 ? o1.getKey().compareTo(o2.getKey()) : o1.getValue().compareTo(o2.getValue()) : o2.getValue().compareTo(o1.getValue()) == 0 ? o2.getKey().compareTo(o1.getKey()) : o2.getValue().compareTo(o1.getValue())); System.out.println("check 2 - list sorted before return = " + list); return list.stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue, (a, b) -> b, LinkedHashMap::new)); } public static void main(String[] args) { Map<Integer, String> map = new IdentityHashMap<Integer, String>(); map.put(new Integer(1), "one"); map.put(new Integer(1), "one"); map.put(new Integer(2), "two"); map.put(new Integer(3), "three"); map.put(new Integer(4), "four"); System.out.println(sortByValue(map,true)); } }
Console output:
As you can see, my two check steps show that duplicates are present, but they disappear on return.check 1 - list = [1=one, 3=three, 2=two, 1=one, 4=four]
check 2 - list sorted before return = [4=four, 1=one, 1=one, 3=three, 2=two]
{4=four, 1=one, 3=three, 2=two}