Posts

Showing posts with the label sort

Sort a Map by value !!

Sorting a Map by value in Java: import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class SortMapByValue { public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("z", 2); map.put("q", 0); map.put("p", 5); map.put("s", 8); map.put("o", 0); map.put("r", 9); map.put("v", 8); System.out.println(map); Set<Entry<String, Integer>> entrySet = map.entrySet(); List<Entry<String, Integer>> lists = new ArrayList<Entry<String, Integer>>(entrySet); Collections.sort(lists, new Comparator<Entry<String, Integer>>() { @Override public int compare(Entry<String, Integer> o1, Entry<String, Integer> o...

Java single field sort using Comparator.

import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; class SortBySalary implements Comparator<Human> { @Override public int compare(Human o1, Human o2) { if (o1.salary > o2.salary) return 1; if (o1.salary < o2.salary) return -1; return 0; } } class Human { String name; int age; double salary; public Human(String n, int a, double s) { this.name = n; this.age = a; this.salary = s; } public Human() { } public String toString() { return this.name + " " + this.age + " " + this.salary; } } public class ComparatorExe { public static void main(String[] args) { List<Human> l = new ArrayList(); Human h1 = new Human("ritesh", 12, 6000); Human h2 = new Human("raju", 18, 5000); Human h3 = new Human("ishaan", 10, 7000); Human h4 = new Human("yuyu", 15, 333); Human h5 = new Hu...