sorting value related question on java collection

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
 
public class SortingValueUsingTreeMap {
	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("before sort values are unsorted as below");
		System.out.println(map);
 
		Map sortedMap = sortByValue(map);
		System.out.println("after sort values are sorted as below");
		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 valueA.compareTo(valueB);
	}
}

Open in new window


above code gave below output

before sort values are unsorted as below
{a=10, b=30, c=50, d=40, e=20}
after sort values are sorted as below
{a=10, e=20, b=30, d=40, c=50}


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 SortingValueUsingComparatorLinkedList {

    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


class Dog  implements Comparable<Dog> {

    String color;


    Dog(String c) {

        color = c;

    }

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

    public String toString(){

        return color + " dog22";

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

};

Open in new window


above code gave output as below

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




I wonder which is better approach to sort based on the value in above mentioned two approaches. Are there are any other approaches existing to sort based on value and also key. please advise
LVL 7
gudii9Asked:
Who is Participating?
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.

Tomas Helgi JohannssonCommented:
Hi!

It all depends on how you want your data to be sorted and the chosen sorting algorithm.
Depending on the volume of data and data structure (maps, trees etc) some sorting algorithms are considerable faster than others.
You can implement multiple compare methods. For example on that sort the data based on the keys and one that sorts the data based on the values. Then you simply call both methods and you have data sorted on both keys and values.

Regards,
    Tomas Helgi
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:
Depending on the volume of data and data structure (maps, trees etc) some sorting algorithms are considerable faster than others

any links, resources around this. please advise
0
gudii9Author Commented:
please advise
0
gudii9Author Commented:
what is the exact difference between above two approaches. please advise
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.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.