Java Written Test Common Class: Comparator Class Implements Array Sorting of Custom Objects

Keywords: Java Lambda JDK less

When writing programs or writing test papers, we always encounter classes or data structures defined by ourselves. If we put classes defined by ourselves into arrays such as List, sorting is very troublesome, such as:
A Person class is defined below.

class Person{
	String name;
	int age;
	public Person(String name,int age) {
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
}

If we want to sort the arrays that store a lot of Person s, we first need to determine the sort rules, which sort is according to, for example, age, name and so on. If we use the conventional method to sort and exchange positions, it is very troublesome. Fortunately, List provides us with sort method. Here is the jdk document.

Parameters:
c - the Comparator used to compare list elements. A null value indicates that the elements' natural ordering should be used

Still, the sort method of List is sorted by a specific Comparator. Sort in the form of list.sort(c), which is the specific Comparator object. Comparator is our criterion for comparison. Now look at the Comparator class.

@FunctionalInterface
public interface Comparator< T>
A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering.

This is a functional interface for comparing two objects, because it is a functional interface, so we can use Lambda expression to implement this interface. If you do not know what a functional interface is or are interested in using Lambda expression, refer to the following blog: Lambda expression

Here's how to implement this interface:

So we write a class to implement the interface and implement the method:

class PersonSortByAge implements Comparator<Person>{
	@Override
	public int compare(Person o1, Person o2) {
		return o1.age-o2.age;
	}
}

That's easy to understand.

  • If the return value equals zero: o1=o2
  • If the return value is greater than zero, O1 > O2
  • If the return value is less than zero, O1 < O2

Then you can sort in the collection:

public class ComparatorTest {

	public static void main(String[] args) {

		List<Person> personList = new ArrayList<Person>();
		personList.add(new Person("ace",22));
		personList.add(new Person("xb",21));
		personList.add(new Person("glm",36));
		personList.add(new Person("sxy",20));
		personList.sort(new PersonSortByAge());
		for(Person p:personList)
			System.out.println(p);
		
	}
}

The results are as follows, arranged according to age.

If you want to try other sorting methods, let me give you an example.

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

/**
* Project name: CSDN
* Package name: Compare
* File name: ComparatorTest.java
* Creation date: 13 April 2019
* 
* @author:	xiatom
* Description: Comparative Method
* 
*
**/

class PersonSortByAgeSmall implements Comparator<Person>{

	@Override
	public int compare(Person o1, Person o2) {
		return o1.age-o2.age;
	}
	
}

class PersonSortByAgeBig implements Comparator<Person>{

	@Override
	public int compare(Person o1, Person o2) {
		return o2.age-o1.age;
	}
	
}

class PersonSortByName implements Comparator<Person>{

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


class Person{
	String name;
	int age;
	public Person(String name,int age) {
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
	
}

public class ComparatorTest {

	public static void main(String[] args) {

		List<Person> personList = new ArrayList<Person>();
		personList.add(new Person("ace",22));
		personList.add(new Person("xb",21));
		personList.add(new Person("glm",36));
		personList.add(new Person("sxy",20));
		System.out.println("According to age, big front row");
		personList.sort(new PersonSortByAgeBig());
		for(Person p:personList)
			System.out.println(p);
		System.out.println();

		System.out.println("According to age, small front row");
		personList.sort(new PersonSortByAgeSmall());
		for(Person p:personList)
			System.out.println(p);
		

		System.out.println();
		System.out.println("Sort by name");
		personList.sort(new PersonSortByName());
		for(Person p:personList)
			System.out.println(p);
		
	}
}

Posted by Octave91 on Fri, 17 May 2019 10:43:29 -0700