Friday, April 27, 2018

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]

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...