Java – Unable to sort the list in ascending order

Unable to sort the list in ascending order… here is a solution to the problem.

Unable to sort the list in ascending order

Map<String, String> map ;
List<Map<String, String>> list = new ArrayList<Map<String, String>>();

OnCreate.............

function1(){
map = new TreeMap<String, String>();
map.put("id", "id");
map.put("amont", "amount");

list.add(map);

System.out.println(list);
}

The input value for id=1,3,5,57,80

The input value of amount=100,500,200,10,10000

You cannot sort the list in ascending order by amount. It still appears in the order in which it was inserted.

How do I fix this? I appreciate any help. Thanks in advance.

Expected output: Amount ascending:

amt=10 id=4  
amt=100 id=1  
amt=200 id=3  
amt=500 id=2  
amt=10000 id=5  

Solution

Let’s say this is your input

  Map<String, String> map ;
  List<Map<String, String>> list = new ArrayList<Map<String, String>>();
  map = new TreeMap<String, String>();
  map.put("id","1");
  map.put("amount","100");
  list.add(map);
  map = new TreeMap<String, String>();
  map.put("id","2");
  map.put("amount","500");  
  list.add(map);
  map = new TreeMap<String, String>();
  map.put("id","3");
  map.put("amount","200");
  list.add(map);
  map = new TreeMap<String, String>();
  map.put("id","4");
  map.put("amount","10");
  list.add(map);
  map = new TreeMap<String, String>();
  map.put("id","5");
  map.put("amount","10000");
  list.add(map);

This is your sort code

  Collections.sort(list, new Comparator<Map<String, String>>() {

@Override
        public int compare(Map<String, String> o1, Map<String, String> o2) {
            String value1 =  o1.get("amount");
            String value2 =  o2.get("amount");
            return Integer.parseInt(value1)-Integer.parseInt(value2);
        }
    });

for (Map<String, String> map1 : list) {
        String id = map1.get("id");
        String amount = map1.get("amount");
        System.out.println("amount= "+amount + " , " +"id = "+id);
    }

Output

amount= 10 , id = 4
amount= 100 , id = 1
amount= 200 , id = 3
amount= 500 , id = 2
amount= 10000 , id = 5

Update

If the value is decimal, return Integer.parseInt(value1)-Integer.parseInt(value2); with the following code.

return Double.valueOf(value1).compareTo(Double.valueOf(value2));

Related Problems and Solutions