Showing posts with label comparator. Show all posts
Showing posts with label comparator. Show all posts

Friday, May 10, 2019

How to sort keys in TreeMap by using Comparator with user define objects?

Problem statement:
How to sort keys in TreeMap by using Comparator with user defined objects.
  1. import java.util.Comparator;
  2. import java.util.Set;
  3. import java.util.TreeMap;
  4. public class SortByKeyUserDefine {
  5.     public static void main(String a[]) {
  6.         //By using name comparator (String comparison)
  7.         System.out.println("========= Sort by name ==============");
  8.         TreeMap<Employee, String> tm = new TreeMap<Employee, String>(new MyNameComp());
  9.         tm.put(new Employee("Ram", 3000), "RAM");
  10.         tm.put(new Employee("John", 6000), "JOHN");
  11.         tm.put(new Employee("Crish", 2000), "CRISH");
  12.         tm.put(new Employee("Tom", 2400), "TOM");
  13.         Set<Employee> keys = tm.keySet();
  14.         for (Employee key : keys) {
  15.             System.out.println(key + " ==> " + tm.get(key));
  16.         }
  17.         System.out.println("========= Sort by salary ==============");
  18.         //By using salary comparator (int comparison)
  19.         TreeMap<Employee, String> trmap = new TreeMap<Employee, String>(new MySalaryComp());
  20.         trmap.put(new Employee("Ram", 3000), "RAM");
  21.         trmap.put(new Employee("John", 6000), "JOHN");
  22.         trmap.put(new Employee("Crish", 2000), "CRISH");
  23.         trmap.put(new Employee("Tom", 2400), "TOM");
  24.         Set<Employee> ks = trmap.keySet();
  25.         for (Employee key : ks) {
  26.             System.out.println(key + " ==> " + trmap.get(key));
  27.         }
  28.     }
  29. }

  30. class MyNameComp implements Comparator<Employee> {
  31.     @Override
  32.     public int compare(Employee e1, Employee e2) {
  33.         return e1.getName().compareTo(e2.getName());
  34.     }
  35. }

  36. class MySalaryComp implements Comparator<Employee> {
  37.     @Override
  38.     public int compare(Employee e1, Employee e2) {
  39.         if (e1.getSalary() > e2.getSalary()) {
  40.             return 1;
  41.         } else {
  42.             return -1;
  43.         }
  44.     }
  45. }

  46. class Employee {
  47.     private String name;
  48.     private int salary;
  49.     public Employee(String n, int s) {
  50.         this.name = n;
  51.         this.salary = s;
  52.     }
  53.     public String getName() {
  54.         return name;
  55.     }
  56.     public void setName(String name) {
  57.         this.name = name;
  58.     }
  59.     public int getSalary() {
  60.         return salary;
  61.     }
  62.     public void setSalary(int salary) {
  63.         this.salary = salary;
  64.     }
  65.     public String toString() {
  66.         return "Name: " + this.name + " , Salary: " + this.salary;
  67.     }
  68. }
Output:
========= Sort by name ==============
Name: Crish , Salary: 2000 ==> CRISH
Name: John , Salary: 6000 ==> JOHN
Name: Ram , Salary: 3000 ==> RAM
Name: Tom , Salary: 2400 ==> TOM
========= Sort by salary ==============
Name: Crish , Salary: 2000 ==> null
Name: Tom , Salary: 2400 ==> null
Name: Ram , Salary: 3000 ==> null
Name: John , Salary: 6000 ==> null

Saturday, April 28, 2018

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> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
System.out.println("--------------------");
for (Map.Entry<String, Integer> entry : lists) {
System.out.println(entry.getKey() + " :: " + entry.getValue());
}
}
}

Output:

{p=5, q=0, r=9, s=8, v=8, z=2, o=0}
--------------------
q :: 0
o :: 0
z :: 2
p :: 5
s :: 8
v :: 8
r :: 9

Sort a HashMap by key !!

Sorting a HashMap by key 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 SortMapByKey {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("z", 1);
map.put("q", 2);
map.put("p", 3);
map.put("s", 4);
map.put("o", 5);
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> o2) {
return (o1.getKey()).compareTo(o2.getKey());
}
});
System.out.println("--------------------");
for (Map.Entry<String, Integer> entry : lists) {
System.out.println(entry.getKey() + " :: " + entry.getValue());
}
}
}

Output: 
{p=3, q=2, s=4, z=1, o=5}
--------------------
o :: 5
p :: 3
q :: 2
s :: 4
z :: 1

Friday, April 27, 2018

Java sort single field 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 Human("yuyu", 17, 333);
Human h6 = new Human("yuyu", 13, 333);
l.add(h1);
l.add(h2);
l.add(h3);
l.add(h4);
l.add(h5);
l.add(h6);

System.out.println(l);

Collections.sort(l, new SortBySalary());
System.out.println(l);
}

}


Output:
[ritesh 12 6000.0, raju 18 5000.0, ishaan 10 7000.0, yuyu 15 333.0, yuyu 17 333.0, yuyu 13 333.0]
[yuyu 15 333.0, yuyu 17 333.0, yuyu 13 333.0, raju 18 5000.0, ritesh 12 6000.0, ishaan 10 7000.0]

Java sort multiple fields using Comparator.

Sort multiple fields using Comparator:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class SortByAnimalName implements Comparator<Animal> {

@Override
public int compare(Animal o1, Animal o2) {
return o1.name.compareTo(o2.name);
}
}

class SortByAnimalColor implements Comparator<Animal> {

@Override
public int compare(Animal o1, Animal o2) {
return o1.color.compareTo(o2.color);
}
}

class SortByAnimalWeight implements Comparator<Animal> {

@Override
public int compare(Animal o1, Animal o2) {
if (o1.weight > o2.weight) {
return 1;
}
if (o1.weight < o2.weight) {
return -1;
}
return 0;
}
}

class SortByAllAnimal implements Comparator<Animal> {

List<Comparator<Animal>> allFields;

@SafeVarargs
SortByAllAnimal(Comparator<Animal>... allSort) {
this.allFields = Arrays.asList(allSort);

}
@Override
public int compare(Animal o1, Animal o2) {
for (Comparator<Animal> x : allFields) {
int res = x.compare(o1, o2);
if (res != 0) {
return res;
}
}
return 0;
}
}

class Animal {
String color;
String name;
int weight;

Animal(String c, String n, int w) {
this.color = c;
this.name = n;
this.weight = w;
}
@Override
public String toString() {
return this.color + " " + this.name + " " + this.weight;
}
}

public class SortMultipleDataByComparator{
public static void main(String[] args) {
List<Animal> l = new ArrayList<Animal>();
Animal a1 = new Animal("black", "dog", 20);
Animal a2 = new Animal("white", "cat", 15);
Animal a3 = new Animal("black", "elephant", 120);
Animal a4 = new Animal("white", "horse", 80);
l.add(a1);
l.add(a2);
l.add(a3);
l.add(a4);
System.out.println(l);
System.out.println("------------------------------------");
Collections.sort(l,
new SortByAllAnimal(new SortByAnimalColor(), new SortByAnimalName(), new SortByAnimalWeight()));

System.out.println(l);
}
}


Output:

[black dog 20, white cat 15, black elephant 120, white horse 80]
------------------------------------
[black dog 20, black elephant 120, white cat 15, white horse 80]

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...