how to sort hashMap

import java.util.HashMap;
import java.util.Map.Entry;



public class TestHashMap {
public static void main(String[] args) {
	//HashMap hashMap = new HashMap();
		
		HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>();
		Dog d1 = new Dog("red");
		Dog d2 = new Dog("black");
		Dog d3 = new Dog("white");
		Dog d4 = new Dog("white");
		
		hashMap.put(d1, 10);
		hashMap.put(d2, 15);
		hashMap.put(d3, 5);
		hashMap.put(d4, 20); 

		//print size
		System.out.println(hashMap.size());
		
		
		for (Entry<Dog, Integer> intval1 : hashMap.entrySet()) {
			System.out.println(intval1.toString() );
			}
		
		//loop HashMap
		for (Integer intval : hashMap.values()) {
		System.out.println(intval.toString() );
		}
		for (Dog keyObj : hashMap.keySet()) {
			System.out.println(keyObj.color );
			
			
			
			/*for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {
			System.out.println(entry.getKey().toString() + " - " + entry.getValue());*/
		}
	}
}

Open in new window

not able to sort on int. i got output as below.
please advise

4
white dog22=5
white dog22=20
black dog22=15
red dog22=10
5
20
15
10
white
white
black
red
LVL 7
gudii9Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ozoCommented:
For sorted output, you'd probably want to use TreeMap instead of HashMap
0
gurpsbassiCommented:
Seems you want to be able to sort the values themselves. Using a TreeMap will give you your values in ascending order of the keys. You may need to write a custom comparator to do this.
0
CEHJCommented:
??

You've just accepted an answer from me that shows a map sorted by value. Why aren't you using the same code ?
0
Fundamentals of JavaScript

Learn the fundamentals of the popular programming language JavaScript so that you can explore the realm of web development.

zzynxSr. Software engineerCommented:
The two first answers at this page should give you all the inspiration you need.
0
gudii9Author Commented:
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortMapByValue
{
    public static boolean ASC = true;
    public static boolean DESC = false;

    public static void main(String[] args)
    {

        // Creating dummy unsorted map
        Map<String, Integer> unsortMap = new HashMap<String, Integer>();
        unsortMap.put("B", 55);
        unsortMap.put("A", 80);
        unsortMap.put("D", 20);
        unsortMap.put("C", 70);

        System.out.println("Before sorting......");
        printMap(unsortMap);

        System.out.println("After sorting ascending order......");
        Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
        printMap(sortedMapDesc);

    }

    private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
    {

        List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());

        // Sorting the list based on values
        Collections.sort(list, new Comparator<Entry<String, Integer>>()
        {
            public int compare(Entry<String, Integer> o1,
                    Entry<String, Integer> o2)
            {
                if (order)
                {
                    return o1.getValue().compareTo(o2.getValue());
                }
                else
                {
                    return o2.getValue().compareTo(o1.getValue());

                }
            }
        });

        // Maintaining insertion order with the help of LinkedList
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Entry<String, Integer> entry : list)
        {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }

    public static void printMap(Map<String, Integer> map)
    {
        for (Entry<String, Integer> entry : map.entrySet())
        {
            System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
        }
    }
}

Open in new window


that link example is sorting on ascending and descending order as below
Before sorting......
Key : A Value : 80
Key : B Value : 55
Key : C Value : 70
Key : D Value : 20
After sorting ascending order......
Key : D Value : 20
Key : B Value : 55
Key : C Value : 70
Key : A Value : 80
After sorting descindeng order......
Key : A Value : 80
Key : C Value : 70
Key : B Value : 55
Key : D Value : 20
0
gudii9Author Commented:
I see above examle using linkedlist

and also below example using treemap

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
 
public class Solution {
	public static void main(String[] args) {
		HashMap<String, Integer> map = new HashMap<String, Integer>();
		map.put("a", 10);
		map.put("b", 30);
		map.put("c", 50);
		map.put("d", 40);
		map.put("e", 20);
		System.out.println(map);
 
		Map sortedMap = sortByValue(map);
		System.out.println(sortedMap);
	}
 
	public static Map sortByValue(Map unsortedMap) {
		Map sortedMap = new TreeMap(new ValueComparator(unsortedMap));
		sortedMap.putAll(unsortedMap);
		return sortedMap;
	}
 
}
 
class ValueComparator implements Comparator {
 
	Map map;
 
	public ValueComparator(Map map) {
		this.map = map;
	}
 
	public int compare(Object keyA, Object keyB) {
		Comparable valueA = (Comparable) map.get(keyA);
		Comparable valueB = (Comparable) map.get(keyB);
		return valueB.compareTo(valueA);
	}
}

Open in new window


i guess there is no other way to make HashMap to sort except implementing linkedlist or treemap
0
gudii9Author Commented:
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;



public class TestHashMap {
public static void main(String[] args) {
	//HashMap hashMap = new HashMap();
		
		HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>();
		Dog d1 = new Dog("red");
		Dog d2 = new Dog("black");
		Dog d3 = new Dog("white");
		Dog d4 = new Dog("white");
		
		hashMap.put(d1, 10);
		hashMap.put(d2, 15);
		hashMap.put(d3, 5);
		hashMap.put(d4, 20); 

		//print size
		System.out.println(hashMap.size());
		
		
		
		
		
		System.out.println("After sorting ascending order......");
        Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
        printMap(sortedMapDesc);
        
        
        
		
		
		for (Entry<Dog, Integer> intval1 : hashMap.entrySet()) {
			System.out.println(intval1.toString() );
			}
		
		//loop HashMap
		for (Integer intval : hashMap.values()) {
		System.out.println(intval.toString() );
		}
		for (Dog keyObj : hashMap.keySet()) {
			System.out.println(keyObj.color );
			
			
			
			/*for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {
			System.out.println(entry.getKey().toString() + " - " + entry.getValue());*/
		}
	}








public static void printMap(Map<String, Integer> map)
{
    for (Entry<String, Integer> entry : map.entrySet())
    {
        System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
    }
}




private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
{

    LinkedList<Entry<String,Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());

    // Sorting the list based on values
    Collections.sort(list, new Comparator<Entry<String, Integer>>()
    {
        public int compare(Entry<String, Integer> o1,
                Entry<String, Integer> o2)
        {
            if (order)
            {
                return o1.getValue().compareTo(o2.getValue());
            }
            else
            {
                return o2.getValue().compareTo(o1.getValue());

            }
        }
    });

    // Maintaining insertion order with the help of LinkedList
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : list)
    {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

    return sortedMap;
}



}




/*package com.rais;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortMapByValue
{
    public static boolean ASC = true;
    public static boolean DESC = false;

    public static void main(String[] args)
    {

        // Creating dummy unsorted map
        Map<String, Integer> unsortMap = new HashMap<String, Integer>();
        unsortMap.put("B", 55);
        unsortMap.put("A", 80);
        unsortMap.put("D", 20);
        unsortMap.put("C", 70);

        System.out.println("Before sorting......");
        printMap(unsortMap);

        System.out.println("After sorting ascending order......");
        Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
        printMap(sortedMapDesc);

    }

    private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
    {

        List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());

        // Sorting the list based on values
        Collections.sort(list, new Comparator<Entry<String, Integer>>()
        {
            public int compare(Entry<String, Integer> o1,
                    Entry<String, Integer> o2)
            {
                if (order)
                {
                    return o1.getValue().compareTo(o2.getValue());
                }
                else
                {
                    return o2.getValue().compareTo(o1.getValue());

                }
            }
        });

        // Maintaining insertion order with the help of LinkedList
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Entry<String, Integer> entry : list)
        {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }

    public static void printMap(Map<String, Integer> map)
    {
        for (Entry<String, Integer> entry : map.entrySet())
        {
            System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
        }
    }
}*/

Open in new window


i was trying as above getting below error. please advise
ultiple markers at this line
      - ASC cannot be resolved to a
       variable
      - unsortMap cannot be resolved to a
       variable
0
zzynxSr. Software engineerCommented:
1) If you use ASC, you have to define it somewhere.
In the example I gave you it is defined as
    public static boolean ASC = true;
    public static boolean DESC = false;

Open in new window


2) Same for the variable 'unsortMap'. You nowhere define it.

3) The method sortByComparator(Map<String, Integer> unsortMap
   is made to take a map having a String as key and an Integer as value.
   Your map uses Dog as key.
   It's clear it won't work. You'll have to change the sortByComparator method accordingly.
0
zzynxSr. Software engineerCommented:
I don't remember your Dog class anymore, but with this simple Dog class:

public class Dog {

    public String color;

    public Dog(String color) {
        this.color = color;
    }

    public String toString() {
        return this.color;
    }
}

Open in new window


and this adapted TestHashMap code:

public class TestHashMap {

    public static boolean ASC = true;
    public static boolean DESC = false;

    public static void main(String[] args) {
        //HashMap hashMap = new HashMap();

        HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>();
        Dog d1 = new Dog("red");
        Dog d2 = new Dog("black");
        Dog d3 = new Dog("white");
        Dog d4 = new Dog("white");

        hashMap.put(d1, 10);
        hashMap.put(d2, 15);
        hashMap.put(d3, 5);
        hashMap.put(d4, 20);

        //print size
        System.out.println(hashMap.size());

        System.out.println("After sorting ascending order......");
        Map<Dog, Integer> sortedMapAsc = sortByComparator(hashMap, ASC);
        printMap(sortedMapAsc);

        System.out.println("After sorting descindeng order......");
        Map<Dog, Integer> sortedMapDesc = sortByComparator(hashMap, DESC);
        printMap(sortedMapDesc);

        for (Entry<Dog, Integer> intval1 : hashMap.entrySet()) {
            System.out.println(intval1.toString() );
        }

        //loop HashMap
        for (Integer intval : hashMap.values()) {
            System.out.println(intval.toString() );
        }
        for (Dog keyObj : hashMap.keySet()) {
            System.out.println(keyObj.color );
        }
    }

    public static void printMap(Map<Dog, Integer> map) {
        for (Entry<Dog, Integer> entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
        }
    }

    private static Map<Dog, Integer> sortByComparator(Map<Dog, Integer> unsortMap, final boolean order) {

        LinkedList<Entry<Dog,Integer>> list = new LinkedList<Entry<Dog, Integer>>(unsortMap.entrySet());

        // Sorting the list based on values
        Collections.sort(list, new Comparator<Entry<Dog, Integer>>()
        {
            public int compare(Entry<Dog, Integer> o1, Entry<Dog, Integer> o2) {
                if (order) {
                    return o1.getValue().compareTo(o2.getValue());
                } else {
                    return o2.getValue().compareTo(o1.getValue());
                }
            }
        });

        // Maintaining insertion order with the help of LinkedList
        Map<Dog, Integer> sortedMap = new LinkedHashMap<Dog, Integer>();
        for (Entry<Dog, Integer> entry : list) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }
        return sortedMap;
    }
}

Open in new window


I get the expected/correct output:

4
After sorting ascending order......
Key : white Value : 5
Key : red Value : 10
Key : black Value : 15
Key : white Value : 20
After sorting descindeng order......
Key : white Value : 20
Key : black Value : 15
Key : red Value : 10
Key : white Value : 5
... (and more)
0
CEHJCommented:
public static boolean ASC = true;

Open in new window

If you're going to do that (moot, as you're making a kind of enumeration which is really not an enumeration), use ASCENDING and use it later on in the code parameters instead of the neutral and confusing 'order', e.g.:

if (order == ASCENDING)

Open in new window

0
gudii9Author Commented:
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;



public class TestHashMap {
private static final boolean ASC = false;
private static final boolean DESC = false;




public static void main(String[] args) {
	//HashMap hashMap = new HashMap();
		
		HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>();
		Dog d1 = new Dog("red");
		Dog d2 = new Dog("black");
		Dog d3 = new Dog("white");
		Dog d4 = new Dog("white");
		
		hashMap.put(d1, 10);
		hashMap.put(d2, 15);
		hashMap.put(d3, 5);
		hashMap.put(d4, 20); 

		//print size
		System.out.println(hashMap.size());
		
		
		
		
		
		System.out.println("After sorting ascending order......");
        Map<String, Integer> unsortMap = null;
		Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
        printMap(sortedMapDesc);
        
        
        
		
		
		for (Entry<Dog, Integer> intval1 : hashMap.entrySet()) {
			System.out.println(intval1.toString() );
			}
		
		//loop HashMap
		for (Integer intval : hashMap.values()) {
		System.out.println(intval.toString() );
		}
		for (Dog keyObj : hashMap.keySet()) {
			System.out.println(keyObj.color );
			
			
			
			/*for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {
			System.out.println(entry.getKey().toString() + " - " + entry.getValue());*/
		}
	}








public static void printMap(Map<String, Integer> map)
{
    for (Entry<String, Integer> entry : map.entrySet())
    {
        System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
    }
}




private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
{

    LinkedList<Entry<String,Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());

    // Sorting the list based on values
    Collections.sort(list, new Comparator<Entry<String, Integer>>()
    {
        public int compare(Entry<String, Integer> o1,
                Entry<String, Integer> o2)
        {
            if (order)
            {
                return o1.getValue().compareTo(o2.getValue());
            }
            else
            {
                return o2.getValue().compareTo(o1.getValue());

            }
        }
    });

    // Maintaining insertion order with the help of LinkedList
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : list)
    {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

    return sortedMap;
}



}




/*package com.rais;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortMapByValue
{
    public static boolean ASC = true;
    public static boolean DESC = false;

    public static void main(String[] args)
    {

        // Creating dummy unsorted map
        Map<String, Integer> unsortMap = new HashMap<String, Integer>();
        unsortMap.put("B", 55);
        unsortMap.put("A", 80);
        unsortMap.put("D", 20);
        unsortMap.put("C", 70);

        System.out.println("Before sorting......");
        printMap(unsortMap);

        System.out.println("After sorting ascending order......");
        Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
        printMap(sortedMapDesc);

    }

    private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
    {

        List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());

        // Sorting the list based on values
        Collections.sort(list, new Comparator<Entry<String, Integer>>()
        {
            public int compare(Entry<String, Integer> o1,
                    Entry<String, Integer> o2)
            {
                if (order)
                {
                    return o1.getValue().compareTo(o2.getValue());
                }
                else
                {
                    return o2.getValue().compareTo(o1.getValue());

                }
            }
        });

        // Maintaining insertion order with the help of LinkedList
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Entry<String, Integer> entry : list)
        {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }

    public static void printMap(Map<String, Integer> map)
    {
        for (Entry<String, Integer> entry : map.entrySet())
        {
            System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
        }
    }
}*/

Open in new window

above code with below Dog class
class Dog {

String color;

Dog(String c) {

	color = c;

}

@Override
public int hashCode() {
	final int prime = 31;
	int result = 1;
	result = prime * result + ((color == null) ? 0 : color.hashCode());
	return result;
}

@Override
public boolean equals(Object obj) {
	if (this == obj)
		return true;
	if (obj == null)
		return false;
	if (getClass() != obj.getClass())
		return false;
	Dog other = (Dog) obj;
	if (color == null) {
		if (other.color != null)
			return false;
	} else if (!color.equals(other.color))
		return false;
	return true;
}

public int compareTo(Dog compareDog) {
    return this.color.compareTo(compareDog.color);
}

public Dog(String string, int i) {
	// TODO Auto-generated constructor stub
}

public String toString() {

	return color + " dog22";

}

}

Open in new window


i got error as below

3
After sorting ascending order......
Exception in thread "main" java.lang.NullPointerException
      at TestHashMap.sortByComparator(TestHashMap.java:92)
      at TestHashMap.main(TestHashMap.java:41)
0
gudii9Author Commented:
import java.util.Arrays;

public class ssssss {

	/**
	 * @param args
	 */

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String mystr[] = { "100", "50", "10", "1000", "400", "300", "200" };
		System.out.println(Arrays.toString(mystr));
		msd(mystr);
		System.out.println(Arrays.toString(mystr));
	}

	public static void msd(String[] a) {
		msd(a, 0, a.length, 0);
	}

	private static void msd(String[] a, int lo, int hi, int d) {

		int N = a.length;

		if (hi <= lo + 1)
			return;
		int[] count = new int[256 + 1];
		for (int i = 0; i < N; i++)
			count[a[i].charAt(d) + 1]++;
		for (int k = 1; k < 256; k++)
			count[k] += count[k - 1];
		//String[] temp = null;
		String[] temp = new String[a.length];
		for (int i = 0; i < N; i++)
			temp[count[a[i].charAt(d)]++] = a[i];
		for (int i = 0; i < N; i++)
			a[i] = temp[i];
		System.out.println("test....");
		for (int i = 0; i < 255; i++)
			msd(a, lo + count[i], lo + count[i + 1], d + 1);
	}

}









public class Dog {

    public String color;

    public Dog(String color) {
        this.color = color;
    }

    public String toString() {
        return this.color;
    }
}

Open in new window



above giving below error as below even though i used simple Dog class

[100, 50, 10, 1000, 400, 300, 200]
test....
test....
Exception in thread "main" java.lang.StringIndexOutOfBoundsException
      at java.lang.String.charAt(String.java:465)
      at ssssss.msd(ssssss.java:31)
      at ssssss.msd(ssssss.java:42)
      at ssssss.msd(ssssss.java:42)
      at ssssss.msd(ssssss.java:20)
      at ssssss.main(ssssss.java:15)
0
gudii9Author Commented:
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;



public class TestHashMap {
private static final boolean ASC = false;
private static final boolean DESC = false;




public static void main(String[] args) {
	//HashMap hashMap = new HashMap();
		
		HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>();
		Dog d1 = new Dog("red");
		Dog d2 = new Dog("black");
		Dog d3 = new Dog("white");
		Dog d4 = new Dog("white");
		
		hashMap.put(d1, 10);
		hashMap.put(d2, 15);
		hashMap.put(d3, 5);
		hashMap.put(d4, 20); 

		//print size
		System.out.println(hashMap.size());
		
		
		
		
		
		System.out.println("After sorting ascending order......");
        Map<String, Integer> unsortMap = null;
		Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
        printMap(sortedMapDesc);
        
        
        
		
		
		for (Entry<Dog, Integer> intval1 : hashMap.entrySet()) {
			System.out.println(intval1.toString() );
			}
		
		//loop HashMap
		for (Integer intval : hashMap.values()) {
		System.out.println(intval.toString() );
		}
		for (Dog keyObj : hashMap.keySet()) {
			System.out.println(keyObj.color );
			
			
			
			/*for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {
			System.out.println(entry.getKey().toString() + " - " + entry.getValue());*/
		}
	}








public static void printMap(Map<String, Integer> map)
{
    for (Entry<String, Integer> entry : map.entrySet())
    {
        System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
    }
}




private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
{

    LinkedList<Entry<String,Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());

    // Sorting the list based on values
    Collections.sort(list, new Comparator<Entry<String, Integer>>()
    {
        public int compare(Entry<String, Integer> o1,
                Entry<String, Integer> o2)
        {
            if (order)
            {
                return o1.getValue().compareTo(o2.getValue());
            }
            else
            {
                return o2.getValue().compareTo(o1.getValue());

            }
        }
    });

    // Maintaining insertion order with the help of LinkedList
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : list)
    {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

    return sortedMap;
}



}




/*package com.rais;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortMapByValue
{
    public static boolean ASC = true;
    public static boolean DESC = false;

    public static void main(String[] args)
    {

        // Creating dummy unsorted map
        Map<String, Integer> unsortMap = new HashMap<String, Integer>();
        unsortMap.put("B", 55);
        unsortMap.put("A", 80);
        unsortMap.put("D", 20);
        unsortMap.put("C", 70);

        System.out.println("Before sorting......");
        printMap(unsortMap);

        System.out.println("After sorting ascending order......");
        Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
        printMap(sortedMapDesc);

    }

    private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
    {

        List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());

        // Sorting the list based on values
        Collections.sort(list, new Comparator<Entry<String, Integer>>()
        {
            public int compare(Entry<String, Integer> o1,
                    Entry<String, Integer> o2)
            {
                if (order)
                {
                    return o1.getValue().compareTo(o2.getValue());
                }
                else
                {
                    return o2.getValue().compareTo(o1.getValue());

                }
            }
        });

        // Maintaining insertion order with the help of LinkedList
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Entry<String, Integer> entry : list)
        {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }

    public static void printMap(Map<String, Integer> map)
    {
        for (Entry<String, Integer> entry : map.entrySet())
        {
            System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
        }
    }
}*/






public class Dog {

    public String color;

    public Dog(String color) {
        this.color = color;
    }

    public String toString() {
        return this.color;
    }
}

Open in new window

i mean above is giving below error

4
After sorting ascending order......
Exception in thread "main" java.lang.NullPointerException
      at TestHashMap.sortByComparator(TestHashMap.java:92)
      at TestHashMap.main(TestHashMap.java:41)
0
gurpsbassiCommented:
Line 41 - you are passing a null map to the method:

Map<String, Integer> unsortMap = null;
Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);

That is casing the exception.
0
gudii9Author Commented:
but why elcipse coplained at line 41 and 92 instead of line 4 as below

at TestHashMap.sortByComparator(TestHashMap.java:92)
      at TestHashMap.main(TestHashMap.java:41)

please advise
0
gudii9Author Commented:
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;



public class TestHashMap {
private static final boolean ASC = false;
private static final boolean DESC = false;




public static void main(String[] args) {
	//HashMap hashMap = new HashMap();
		
		HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>();
		Dog d1 = new Dog("red");
		Dog d2 = new Dog("black");
		Dog d3 = new Dog("white");
		Dog d4 = new Dog("white");
		
		hashMap.put(d1, 10);
		hashMap.put(d2, 15);
		hashMap.put(d3, 5);
		hashMap.put(d4, 20); 

		//print size
		System.out.println(hashMap.size());
		
		
		
		
		
		System.out.println("After sorting ascending order......");
       // Map<String, Integer> unsortMap = null;
		Map<String, Integer> sortedMapAsc = sortByComparator(hashMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(hashMap, DESC);
        printMap(sortedMapDesc);
        
        
        
		
		
		for (Entry<Dog, Integer> intval1 : hashMap.entrySet()) {
			System.out.println(intval1.toString() );
			}
		
		//loop HashMap
		for (Integer intval : hashMap.values()) {
		System.out.println(intval.toString() );
		}
		for (Dog keyObj : hashMap.keySet()) {
			System.out.println(keyObj.color );
			
			
			
			/*for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {
			System.out.println(entry.getKey().toString() + " - " + entry.getValue());*/
		}
	}








public static void printMap(Map<String, Integer> map)
{
    for (Entry<String, Integer> entry : map.entrySet())
    {
        System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
    }
}




private static Map<String, Integer> sortByComparator(HashMap<Dog, Integer> hashMap, final boolean order)
{

    LinkedList<Entry<String,Integer>> list = new LinkedList<Entry<String, Integer>>();

    // Sorting the list based on values
    Collections.sort(list, new Comparator<Entry<String, Integer>>()
    {
        public int compare(Entry<String, Integer> o1,
                Entry<String, Integer> o2)
        {
            if (order)
            {
                return o1.getValue().compareTo(o2.getValue());
            }
            else
            {
                return o2.getValue().compareTo(o1.getValue());

            }
        }
    });

    // Maintaining insertion order with the help of LinkedList
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : list)
    {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

    return sortedMap;
}



}




/*package com.rais;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortMapByValue
{
    public static boolean ASC = true;
    public static boolean DESC = false;

    public static void main(String[] args)
    {

        // Creating dummy unsorted map
        Map<String, Integer> unsortMap = new HashMap<String, Integer>();
        unsortMap.put("B", 55);
        unsortMap.put("A", 80);
        unsortMap.put("D", 20);
        unsortMap.put("C", 70);

        System.out.println("Before sorting......");
        printMap(unsortMap);

        System.out.println("After sorting ascending order......");
        Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
        printMap(sortedMapDesc);

    }

    private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
    {

        List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());

        // Sorting the list based on values
        Collections.sort(list, new Comparator<Entry<String, Integer>>()
        {
            public int compare(Entry<String, Integer> o1,
                    Entry<String, Integer> o2)
            {
                if (order)
                {
                    return o1.getValue().compareTo(o2.getValue());
                }
                else
                {
                    return o2.getValue().compareTo(o1.getValue());

                }
            }
        });

        // Maintaining insertion order with the help of LinkedList
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Entry<String, Integer> entry : list)
        {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }

    public static void printMap(Map<String, Integer> map)
    {
        for (Entry<String, Integer> entry : map.entrySet())
        {
            System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
        }
    }
}*/

Open in new window


i changed like above based on eclipse suggestion got below output
4
After sorting ascending order......
After sorting descindeng order......
white=5
red=10
white=20
black=15
5
10
20
15
white
red
white
black


not sure why ascending is not coming. Even descending seems not correct
0
gudii9Author Commented:
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;



public class TestHashMap {
private static final boolean ASC = false;
private static final boolean DESC = false;




public static void main(String[] args) {
	//HashMap hashMap = new HashMap();
		
		HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>();
		Dog d1 = new Dog("red");
		Dog d2 = new Dog("black");
		Dog d3 = new Dog("white");
		Dog d4 = new Dog("white");
		
		hashMap.put(d1, 10);
		hashMap.put(d2, 15);
		hashMap.put(d3, 5);
		hashMap.put(d4, 20); 

		//print size
		System.out.println(hashMap.size());
		
		
		
		
		
		System.out.println("After sorting ascending order......");
       // Map<String, Integer> unsortMap = null;
		Map<String, Integer> sortedMapAsc = sortByComparator(hashMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(hashMap, DESC);
        printMap(sortedMapDesc);
        
        
        
		
		
		for (Entry<Dog, Integer> intval1 : hashMap.entrySet()) {
			System.out.println(intval1.toString() );
			}
		
		//loop HashMap
		for (Integer intval : hashMap.values()) {
		System.out.println(intval.toString() );
		}
		for (Dog keyObj : hashMap.keySet()) {
			System.out.println(keyObj.color );
			
			
			
			/*for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {
			System.out.println(entry.getKey().toString() + " - " + entry.getValue());*/
		}
	}








public static void printMap(Map<String, Integer> map)
{
    for (Entry<String, Integer> entry : map.entrySet())
    {
        System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
    }
}




private static Map<String, Integer> sortByComparator(HashMap<Dog, Integer> hashMap, final boolean order)
{

    LinkedList<Entry<String,Integer>> list = new LinkedList<Entry<String, Integer>>();

    // Sorting the list based on values
    Collections.sort(list, new Comparator<Entry<String, Integer>>()
    {
        public int compare(Entry<String, Integer> o1,
                Entry<String, Integer> o2)
        {
            if (order)
            {
                return o1.getValue().compareTo(o2.getValue());
            }
            else
            {
                return o2.getValue().compareTo(o1.getValue());

            }
        }
    });

    // Maintaining insertion order with the help of LinkedList
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : list)
    {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

    return sortedMap;
}



}




/*package com.rais;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortMapByValue
{
    public static boolean ASC = true;
    public static boolean DESC = false;

    public static void main(String[] args)
    {

        // Creating dummy unsorted map
        Map<String, Integer> unsortMap = new HashMap<String, Integer>();
        unsortMap.put("B", 55);
        unsortMap.put("A", 80);
        unsortMap.put("D", 20);
        unsortMap.put("C", 70);

        System.out.println("Before sorting......");
        printMap(unsortMap);

        System.out.println("After sorting ascending order......");
        Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
        printMap(sortedMapDesc);

    }

    private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
    {

        List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());

        // Sorting the list based on values
        Collections.sort(list, new Comparator<Entry<String, Integer>>()
        {
            public int compare(Entry<String, Integer> o1,
                    Entry<String, Integer> o2)
            {
                if (order)
                {
                    return o1.getValue().compareTo(o2.getValue());
                }
                else
                {
                    return o2.getValue().compareTo(o1.getValue());

                }
            }
        });

        // Maintaining insertion order with the help of LinkedList
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Entry<String, Integer> entry : list)
        {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }

    public static void printMap(Map<String, Integer> map)
    {
        for (Entry<String, Integer> entry : map.entrySet())
        {
            System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
        }
    }
}*/

Open in new window


class Dog {

String color;

Dog(String c) {

	color = c;

}

@Override
public int hashCode() {
	final int prime = 31;
	int result = 1;
	result = prime * result + ((color == null) ? 0 : color.hashCode());
	return result;
}

@Override
public boolean equals(Object obj) {
	if (this == obj)
		return true;
	if (obj == null)
		return false;
	if (getClass() != obj.getClass())
		return false;
	Dog other = (Dog) obj;
	if (color == null) {
		if (other.color != null)
			return false;
	} else if (!color.equals(other.color))
		return false;
	return true;
}

public int compareTo(Dog compareDog) {
    return this.color.compareTo(compareDog.color);
}

public Dog(String string, int i) {
	// TODO Auto-generated constructor stub
}

public String toString() {

	return color + " dog22";

}

}

Open in new window


when i change Dog class got below output

3
After sorting ascending order......
After sorting descindeng order......
red dog22=10
white dog22=20
black dog22=15
10
20
15
red
white
black


please advise
0
gudii9Author Commented:
If you're going to do that (moot, as you're making a kind of enumeration which is really not an enumeration), use ASCENDING and use it later on in the code parameters instead of the neutral and confusing 'order', e.g.:

Open in new window


sorry. i did not get what you said. can you please elaborate
0
CEHJCommented:
LinkedList<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>();

Open in new window

That remains empty, which is why sorting never happens. When it is fixed you will find there is only one sort order as your booleans are BOTH false
0
gudii9Author Commented:
LinkedList<Entry<String,Integer>> list = new LinkedList<Entry<String, Integer>>();

how to pass some values to it.

I can make one of them true. Both false is auto generated by eclipse
0
gudii9Author Commented:
Map<String, Integer> sortedMapAsc = sortByComparator(hashMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(hashMap, DESC);
        printMap(sortedMapDesc);

i am calling as above not sure why nothing is getting passed(i though hashMap should be passed to it.please advise
0
gudii9Author Commented:
i wonder why we need again LinkedList collection object to make HashMap to sort .
Is there is any other alternative way we can achieve sorting without using LinkedList
please advise
0
CEHJCommented:
You're making life more difficult for yourself by not using Dog in your List

There isn't a way without a List really
0
gudii9Author Commented:
You're making life more difficult for yourself by not using Dog in your List

i think i got what you are saying to replace String with Dog as Dog object is key in my case but not String.

I did as below

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;



public class TestHashMap {
private static final boolean ASC = false;
private static final boolean DESC = false;




public static void main(String[] args) {
	//HashMap hashMap = new HashMap();
		
		HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>();
		Dog d1 = new Dog("red");
		Dog d2 = new Dog("black");
		Dog d3 = new Dog("white");
		Dog d4 = new Dog("white");
		
		hashMap.put(d1, 10);
		hashMap.put(d2, 15);
		hashMap.put(d3, 5);
		hashMap.put(d4, 20); 

		//print size
		System.out.println(hashMap.size());
		
		
		
		
		
		System.out.println("After sorting ascending order......");
       // Map<String, Integer> unsortMap = null;
		Map<Dog, Integer> sortedMapAsc = sortByComparator(hashMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<Dog, Integer> sortedMapDesc = sortByComparator(hashMap, DESC);
        printMap(sortedMapDesc);
        
        
        
		
		
		for (Entry<Dog, Integer> intval1 : hashMap.entrySet()) {
			System.out.println(intval1.toString() );
			}
		
		//loop HashMap
		for (Integer intval : hashMap.values()) {
		System.out.println(intval.toString() );
		}
		for (Dog keyObj : hashMap.keySet()) {
			System.out.println(keyObj.color );
			
			
			
			/*for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {
			System.out.println(entry.getKey().toString() + " - " + entry.getValue());*/
		}
	}








public static void printMap(Map<Dog, Integer> sortedMapDesc)
{
    for (Entry<Dog, Integer> entry : sortedMapDesc.entrySet())
    {
        System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
    }
}




private static Map<Dog, Integer> sortByComparator(HashMap<Dog, Integer> hashMap, final boolean order)
{

    LinkedList<Entry<String,Integer>> list = new LinkedList<Entry<String, Integer>>();

    // Sorting the list based on values
    Collections.sort(list, new Comparator<Entry<String, Integer>>()
    {
        public int compare(Entry<String, Integer> o1,
                Entry<String, Integer> o2)
        {
            if (order)
            {
                return o1.getValue().compareTo(o2.getValue());
            }
            else
            {
                return o2.getValue().compareTo(o1.getValue());

            }
        }
    });

    // Maintaining insertion order with the help of LinkedList
    Map<Dog, Integer> sortedMap = new LinkedHashMap<Dog, Integer>();
    for (Entry<String, Integer> entry : list)
    {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

    return sortedMap;
}



}




/*package com.rais;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortMapByValue
{
    public static boolean ASC = true;
    public static boolean DESC = false;

    public static void main(String[] args)
    {

        // Creating dummy unsorted map
        Map<String, Integer> unsortMap = new HashMap<String, Integer>();
        unsortMap.put("B", 55);
        unsortMap.put("A", 80);
        unsortMap.put("D", 20);
        unsortMap.put("C", 70);

        System.out.println("Before sorting......");
        printMap(unsortMap);

        System.out.println("After sorting ascending order......");
        Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
        printMap(sortedMapDesc);

    }

    private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
    {

        List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());

        // Sorting the list based on values
        Collections.sort(list, new Comparator<Entry<String, Integer>>()
        {
            public int compare(Entry<String, Integer> o1,
                    Entry<String, Integer> o2)
            {
                if (order)
                {
                    return o1.getValue().compareTo(o2.getValue());
                }
                else
                {
                    return o2.getValue().compareTo(o1.getValue());

                }
            }
        });

        // Maintaining insertion order with the help of LinkedList
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Entry<String, Integer> entry : list)
        {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }

    public static void printMap(Map<String, Integer> map)
    {
        for (Entry<String, Integer> entry : map.entrySet())
        {
            System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
        }
    }
}*/

Open in new window


i am getting below error at line 116

The method put(Dog, Integer) in the type Map<Dog,Integer> is not applicable for the arguments (String, Integer)

please advise

There isn't a way without a List really

sorry i did not understand this. can you please elaborate
0
CEHJCommented:
Now you're returning a Map with Dog as key, you can actually use a TreeMap with a Comparator<Dog> and order the keys based on the values
0
gudii9Author Commented:
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;



public class TestHashMap {
private static final boolean ASC = false;
private static final boolean DESC = false;




public static void main(String[] args) {
	//HashMap hashMap = new HashMap();
		
		HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>();
		Dog d1 = new Dog("red");
		Dog d2 = new Dog("black");
		Dog d3 = new Dog("white");
		Dog d4 = new Dog("white");
		
		hashMap.put(d1, 10);
		hashMap.put(d2, 15);
		hashMap.put(d3, 5);
		hashMap.put(d4, 20); 

		//print size
		System.out.println(hashMap.size());
		
		
		
		
		
		System.out.println("After sorting ascending order......");
       // Map<String, Integer> unsortMap = null;
		Map<Dog, Integer> sortedMapAsc = sortByComparator(hashMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<Dog, Integer> sortedMapDesc = sortByComparator(hashMap, DESC);
        printMap(sortedMapDesc);
        
        
        
		
		
		for (Entry<Dog, Integer> intval1 : hashMap.entrySet()) {
			System.out.println(intval1.toString() );
			}
		
		//loop HashMap
		for (Integer intval : hashMap.values()) {
		System.out.println(intval.toString() );
		}
		for (Dog keyObj : hashMap.keySet()) {
			System.out.println(keyObj.color );
			
			
			
			/*for (Map.Entry<Dog, Integer> entry : hashMap.entrySet()) {
			System.out.println(entry.getKey().toString() + " - " + entry.getValue());*/
		}
	}








public static void printMap(Map<Dog, Integer> sortedMapDesc)
{
    for (Entry<Dog, Integer> entry : sortedMapDesc.entrySet())
    {
        System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
    }
}




private static Map<Dog, Integer> sortByComparator(HashMap<Dog, Integer> hashMap, final boolean order)
{

    LinkedList<Entry<Dog,Integer>> list = new LinkedList<Entry<Dog, Integer>>();

    // Sorting the list based on values
    Collections.sort(list, new Comparator<Entry<Dog, Integer>>()
    {
        public int compare(Entry<Dog, Integer> o1,
                Entry<Dog, Integer> o2)
        {
            if (order)
            {
                return o1.getValue().compareTo(o2.getValue());
            }
            else
            {
                return o2.getValue().compareTo(o1.getValue());

            }
        }
    });

    // Maintaining insertion order with the help of LinkedList
    Map<Dog, Integer> sortedMap = new LinkedHashMap<Dog, Integer>();
    for (Entry<Dog, Integer> entry : list)
    {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

    return sortedMap;
}



}

Open in new window


i got wrong output as below

3
After sorting ascending order......
After sorting descindeng order......
red dog22=10
white dog22=20
black dog22=15
10
20
15
red
white
black


please advise

Now you're returning a Map with Dog as key, you can actually use a TreeMap with a Comparator<Dog> and order the keys based on the values

i need to think about how to do it.
0
CEHJCommented:
You've actually posted code in a recent question that does exactly that - successfully. Have a look
0
zzynxSr. Software engineerCommented:
You know, gudii9.
In the comment with ID: 40735203 I posted a corrected Dog and TestHashMap class (in which I put some work) that simply do the job.
In your next comment you again post a Dog and TestHashMap class (that absolutely differ from mine) telling us that it gives problems...
It's frustrating to see that you don't try to use/understand the code that I post.
Please, look at the differences between my code and yours. That's the reason why you have the errors.
0
gudii9Author Commented:
when i used that code as it is, it is not compiling eventhough everything is in place there as attached at line 34, 48, 55, 60 etc
import java.util.HashMap;
import java.util.Map;

public class TestHashMap {

    public static boolean ASC = true;
    public static boolean DESC = false;

    public static void main(String[] args) {
        //HashMap hashMap = new HashMap();

        HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>();
        Dog d1 = new Dog("red");
        Dog d2 = new Dog("black");
        Dog d3 = new Dog("white");
        Dog d4 = new Dog("white");

        hashMap.put(d1, 10);
        hashMap.put(d2, 15);
        hashMap.put(d3, 5);
        hashMap.put(d4, 20);

        //print size
        System.out.println(hashMap.size());

        System.out.println("After sorting ascending order......");
        Map<Dog, Integer> sortedMapAsc = sortByComparator(hashMap, ASC);
        printMap(sortedMapAsc);

        System.out.println("After sorting descindeng order......");
        Map<Dog, Integer> sortedMapDesc = sortByComparator(hashMap, DESC);
        printMap(sortedMapDesc);

        for (Entry<Dog, Integer> intval1 : hashMap.entrySet()) {
            System.out.println(intval1.toString() );
        }

        //loop HashMap
        for (Integer intval : hashMap.values()) {
            System.out.println(intval.toString() );
        }
        for (Dog keyObj : hashMap.keySet()) {
            System.out.println(keyObj.color );
        }
    }

    public static void printMap(Map<Dog, Integer> map) {
        for (Entry<Dog, Integer> entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
        }
    }

    private static Map<Dog, Integer> sortByComparator(Map<Dog, Integer> unsortMap, final boolean order) {

        LinkedList<Entry<Dog,Integer>> list = new LinkedList<Entry<Dog, Integer>>(unsortMap.entrySet());

        // Sorting the list based on values
        Collections.sort(list, new Comparator<Entry<Dog, Integer>>()
        {
            public int compare(Entry<Dog, Integer> o1, Entry<Dog, Integer> o2) {
                if (order) {
                    return o1.getValue().compareTo(o2.getValue());
                } else {
                    return o2.getValue().compareTo(o1.getValue());
                }
            }
        });

        // Maintaining insertion order with the help of LinkedList
        Map<Dog, Integer> sortedMap = new LinkedHashMap<Dog, Integer>();
        for (Entry<Dog, Integer> entry : list) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }
        return sortedMap;
    }
}

Open in new window


public class Dog {

    public String color;

    public Dog(String color) {
        this.color = color;
    }

    public String toString() {
        return this.color;
    }
}

Open in new window


please advise
Err.jpg
0
zzynxSr. Software engineerCommented:
Are you sure you have this import:

import java.util.Map.Entry;

Open in new window

0
gurpsbassiCommented:
This is quite painful.
Gudii9 would be interesting to know what your background is I.e are you new to java or new to computer programming? Any academic computer sci background?
0
gudii9Author Commented:
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.ibm.rmi.util.list.LinkedList;

public class TestHashMap {

    public static boolean ASC = true;
    public static boolean DESC = false;

    public static void main(String[] args) {
        //HashMap hashMap = new HashMap();

        HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>();
        Dog d1 = new Dog("red");
        Dog d2 = new Dog("black");
        Dog d3 = new Dog("white");
        Dog d4 = new Dog("white");

        hashMap.put(d1, 10);
        hashMap.put(d2, 15);
        hashMap.put(d3, 5);
        hashMap.put(d4, 20);

        //print size
        System.out.println(hashMap.size());

        System.out.println("After sorting ascending order......");
        Map<Dog, Integer> sortedMapAsc = sortByComparator(hashMap, ASC);
        printMap(sortedMapAsc);

        System.out.println("After sorting descindeng order......");
        Map<Dog, Integer> sortedMapDesc = sortByComparator(hashMap, DESC);
        printMap(sortedMapDesc);

        for (Entry<Dog, Integer> intval1 : hashMap.entrySet()) {
            System.out.println(intval1.toString() );
        }

        //loop HashMap
        for (Integer intval : hashMap.values()) {
            System.out.println(intval.toString() );
        }
        for (Dog keyObj : hashMap.keySet()) {
            System.out.println(keyObj.color );
        }
    }

    public static void printMap(Map<Dog, Integer> map) {
        for (Entry<Dog, Integer> entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
        }
    }

    private static Map<Dog, Integer> sortByComparator(Map<Dog, Integer> unsortMap, final boolean order) {

        LinkedList<Entry<Dog,Integer>> list = new LinkedList<Entry<Dog, Integer>>(unsortMap.entrySet());

        // Sorting the list based on values
        Collections.sort(list, new Comparator<Entry<Dog, Integer>>()
        {
            public int compare(Entry<Dog, Integer> o1, Entry<Dog, Integer> o2) {
                if (order) {
                    return o1.getValue().compareTo(o2.getValue());
                } else {
                    return o2.getValue().compareTo(o1.getValue());
                }
            }
        });

        // Maintaining insertion order with the help of LinkedList
        Map<Dog, Integer> sortedMap = new LinkedHashMap<Dog, Integer>();
        for (Entry<Dog, Integer> entry : list) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }
        return sortedMap;
    }
}

Open in new window


i tried now one error at line
61 saying
Multiple markers at this line
      - The type LinkedList is not generic; it cannot be parameterized with arguments
       <Map.Entry<Dog,Integer>>

please advise
0
gudii9Author Commented:
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.ibm.rmi.util.list.LinkedList;

public class TestHashMap {

    public static boolean ASC = true;
    public static boolean DESC = false;

    public static void main(String[] args) {
        //HashMap hashMap = new HashMap();

        HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>();
        Dog d1 = new Dog("red");
        Dog d2 = new Dog("black");
        Dog d3 = new Dog("white");
        Dog d4 = new Dog("white");

        hashMap.put(d1, 10);
        hashMap.put(d2, 15);
        hashMap.put(d3, 5);
        hashMap.put(d4, 20);

        //print size
        System.out.println(hashMap.size());

        System.out.println("After sorting ascending order......");
        Map<Dog, Integer> sortedMapAsc = sortByComparator(hashMap, ASC);
        printMap(sortedMapAsc);

        System.out.println("After sorting descindeng order......");
        Map<Dog, Integer> sortedMapDesc = sortByComparator(hashMap, DESC);
        printMap(sortedMapDesc);

        for (Entry<Dog, Integer> intval1 : hashMap.entrySet()) {
            System.out.println(intval1.toString() );
        }

        //loop HashMap
        for (Integer intval : hashMap.values()) {
            System.out.println(intval.toString() );
        }
        for (Dog keyObj : hashMap.keySet()) {
            System.out.println(keyObj.color );
        }
    }

    public static void printMap(Map<Dog, Integer> map) {
        for (Entry<Dog, Integer> entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
        }
    }

    private static Map<Dog, Integer> sortByComparator(Map<Dog, Integer> unsortMap, final boolean order) {

        LinkedList<Entry<Dog,Integer>> list = new LinkedList(unsortMap.entrySet());

        // Sorting the list based on values
        Collections.sort(list, new Comparator<Entry<Dog, Integer>>()
        {
            public int compare(Entry<Dog, Integer> o1, Entry<Dog, Integer> o2) {
                if (order) {
                    return o1.getValue().compareTo(o2.getValue());
                } else {
                    return o2.getValue().compareTo(o1.getValue());
                }
            }
        });

        // Maintaining insertion order with the help of LinkedList
        Map<Dog, Integer> sortedMap = new LinkedHashMap<Dog, Integer>();
        for (Entry<Dog, Integer> entry : list) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }
        return sortedMap;
    }
}

Open in new window


i removed the type arguments as above stil having issue at same line 61. please advise
0
CEHJCommented:
As has already been explained (and demonstrated), you don't need a List - you can use a TreeMap

If you did need a List, why would you be using one from a foreign (IBM) package?
0
gudii9Author Commented:
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;



public class TestHashMap {

    public static boolean ASC = true;
    public static boolean DESC = false;

    public static void main(String[] args) {
        //HashMap hashMap = new HashMap();

        HashMap<Dog, Integer> hashMap = new HashMap<Dog, Integer>();
        Dog d1 = new Dog("red");
        Dog d2 = new Dog("black");
        Dog d3 = new Dog("white");
        Dog d4 = new Dog("white");

        hashMap.put(d1, 10);
        hashMap.put(d2, 15);
        hashMap.put(d3, 5);
        hashMap.put(d4, 20);

        //print size
        System.out.println(hashMap.size());

        System.out.println("After sorting ascending order......");
        Map<Dog, Integer> sortedMapAsc = sortByComparator(hashMap, ASC);
        printMap(sortedMapAsc);

        System.out.println("After sorting descindeng order......");
        Map<Dog, Integer> sortedMapDesc = sortByComparator(hashMap, DESC);
        printMap(sortedMapDesc);

        for (Entry<Dog, Integer> intval1 : hashMap.entrySet()) {
            System.out.println(intval1.toString() );
        }

        //loop HashMap
        for (Integer intval : hashMap.values()) {
            System.out.println(intval.toString() );
        }
        for (Dog keyObj : hashMap.keySet()) {
            System.out.println(keyObj.color );
        }
    }

    public static void printMap(Map<Dog, Integer> map) {
        for (Entry<Dog, Integer> entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
        }
    }

    private static Map<Dog, Integer> sortByComparator(Map<Dog, Integer> unsortMap, final boolean order) {

        LinkedList<Entry<Dog,Integer>> list = new LinkedList(unsortMap.entrySet());

        // Sorting the list based on values
        Collections.sort(list, new Comparator<Entry<Dog, Integer>>()
        {
            public int compare(Entry<Dog, Integer> o1, Entry<Dog, Integer> o2) {
                if (order) {
                    return o1.getValue().compareTo(o2.getValue());
                } else {
                    return o2.getValue().compareTo(o1.getValue());
                }
            }
        });

        // Maintaining insertion order with the help of LinkedList
        Map<Dog, Integer> sortedMap = new LinkedHashMap<Dog, Integer>();
        for (Entry<Dog, Integer> entry : list) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }
        return sortedMap;
    }
}

Open in new window


above produced
4
After sorting ascending order......
Key : white dog22 Value : 5
Key : red dog22 Value : 10
Key : black dog22 Value : 15
Key : white dog22 Value : 20
After sorting descindeng order......
Key : white dog22 Value : 20
Key : black dog22 Value : 15
Key : red dog22 Value : 10
Key : white dog22 Value : 5
white dog22=5
red dog22=10
black dog22=15
white dog22=20
5
10
15
20
white
red
black
white

it resolved compilation errors. I did wrong import earlier.

but i wonder why sorting not happening while uisng above code. i have HashMap, HashMap and also compareTo() methods as well,Please advise
0
CEHJCommented:
but i wonder why sorting not happening while uisng above code.

Err.. it IS working ...
0
gudii9Author Commented:
So it is sorting on value which is integer here not sorting on key which is dog object.  Please advise
0
CEHJCommented:
not able to sort on int.
Was the problem you reported. So yes, it IS sorting by the integer value - so your problem is solved
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
gudii9Author Commented:
@
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.