-3

This is the code to sort HashMap by Value.

public class LongestChain
{
public static void main(String[] args)
{
    String words[] = new String[]{"a","b", "c", "ca","ba","bca","bda","bdca"};
    System.out.println(longestChainOfWords(words));
}

public static int longestChainOfWords(String words[])
{
    Map<String, Integer> map = new HashMap<String, Integer>();

    for(String a:words)
    {
        map.put(a, a.length());
    }

    System.out.println(map);

    Map sortedMap = sortByValue(map);
    System.out.println(sortedMap);



    return sortedMap.size();
}

public static Map<String, Integer> sortByValue(Map<String, Integer> unsortedMap) 
{
    Map<String, Integer> sortedMap = new TreeMap<String, Integer>(new ValueComparator(unsortedMap));
    sortedMap.putAll(unsortedMap);
    return sortedMap;
}

}

class ValueComparator implements Comparator 
{
    Map<String, Integer> map;

    public ValueComparator(Map<String, Integer> map)
    {
        this.map = map;
    }

    public int compare(Object keyA, Object keyB)
    {
        Comparable valueA = map.get(keyA);
        Comparable valueB = map.get(keyB);
        System.out.println(keyA+" keyA "); System.out.println(keyB+" keyB ");
        return valueA.compareTo(valueB);
    }

}

Output is like this. I was expecting 8 elements in sortedMap too. Why the behavior is like this?

{ca=2, bda=3, ba=2, b=1, c=1, a=1, bdca=4, bca=3} {b=1, ca=2, bda=3, bdca=4} 4

Don Roby
  • 40,677
  • 6
  • 91
  • 113

1 Answers1

0

Because you let the TreeMap think it sorts keys. And if the key is equal the no new value will be put inside. As you have 4 different values, so you can find 4 results in your list.

What you can do is improve the compare - method so equal values will be ordered by their keys:

class ValueComparator implements Comparator<String> {
    Map<String, Integer> map;

    public ValueComparator(final Map<String, Integer> map) {
        this.map = map;
    }

    @Override
    public int compare(final String keyA, final String keyB) {
        final Integer valueA = this.map.get(keyA);
        final Integer valueB = this.map.get(keyB);
        System.out.println(keyA + " keyA ");
        System.out.println(keyB + " keyB ");
        final int compared = valueA.compareTo(valueB);
        if (compared != 0) {
            return compared;
        } else {
            return keyA.compareTo(keyB);
        }
    }

}
Denis Lukenich
  • 3,084
  • 1
  • 20
  • 38