Java collection multi fields sorting
Sorting a list by multiple fields using Comparator on the Collection. For example, a list of person object which has name and age, group the list by name and then sort the person within that name by age.
Input:
Name: ccc Age: 51 Name: ccc Age: 35 Name: aaa Age: 19 Name: bbb Age: 7 Name: bbb Age: 94 Name: bbb Age: 60 Name: aaa Age: 85 Name: bbb Age: 49 Name: aaa Age: 82
Output:
Name: aaa Age: 19 Name: aaa Age: 82 Name: aaa Age: 85 Name: bbb Age: 7 Name: bbb Age: 49 Name: bbb Age: 60 Name: bbb Age: 94 Name: ccc Age: 35 Name: ccc Age: 51
The Person.java
public class Person implements Comparable{ private String name; private int age; public Person(String n, int a) { this.name = n; this.age = a; } public String toString() { return "Name: " + name + " Age: " + age; } public String getName() { return name; } public int getAge() { return age; } @Override public int compareTo(Person another) { int sComp = this.name.compareTo(another.name); // sort by name first and then age if (sComp != 0) { return sComp; } else { Integer age1 = this.getAge(); Integer age2 = another.getAge(); return age1.compareTo(age2); } } }
MultiFieldSort.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;
public class MultiFieldSort {
public static void main(String args[]) {
int maxAge = 100;
int maxNameLength = 10;
int sampeSize = 100;
Random random = new Random();
ArrayList people = new ArrayList();
for (int i=0; i() {
//
// public int compare(Object o1, Object o2) {
//
// String name1 = ((Person) o1).getName();
// String name2 = ((Person) o2).getName();
// int sComp = name1.compareTo(name2);
//
// if (sComp != 0) {
// return sComp;
// } else {
// Integer age1 = ((Person) o1).getAge();
// Integer age2 = ((Person) o2).getAge();
// return age1.compareTo(age2);
// }
// }});
for (Person p : people) {
System.out.println(p.toString());
}
}
public static String generateName() {
Random random = new Random();
String [] names = {"aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk", "lll", "mmm", "nnn"};
return new String(names[random.nextInt(names.length)]);
}
public static String generateString(int maxLength) {
Random random = new Random();
int length = random.nextInt(maxLength);
String characters = "abcdefghijklmnopqrstuvwxyz";
char[] text = new char[length];
for (int i = 0; i < length; i++) {
text[i] = characters.charAt(random.nextInt(characters.length()));
}
return new String(text);
}
}
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts