Implement Comparator interface and usage instance in Java (simple to understand)

  • 2020-04-01 03:50:43
  • OfStack

In Java, if you want to sort a collection object or an array object, you need to implement the Comparator interface to achieve what you want.

Next we simulate sorting the date properties in the collection object

I. entity class Step


package com.ljq.entity;



public class Step{
  
  private String acceptTime = "";
  
  private String acceptAddress = "";

  public Step() {
    super();
  }

  public Step(String acceptTime, String acceptAddress) {
    super();
    this.acceptTime = acceptTime;
    this.acceptAddress = acceptAddress;
  }

  public String getAcceptTime() {
    return acceptTime;
  }

  public void setAcceptTime(String acceptTime) {
    this.acceptTime = acceptTime;
  }

  public String getAcceptAddress() {
    return acceptAddress;
  }

  public void setAcceptAddress(String acceptAddress) {
    this.acceptAddress = acceptAddress;
  }

}

Implement Comparator interface


package com.ljq.entity;

import java.util.Comparator;
import java.util.Date;

import com.ljq.util.UtilTool;


public class StepComparator implements Comparator<Step>{

  
  @Override
  public int compare(Step o1, Step o2) {
    Date acceptTime1=UtilTool.strToDate(o1.getAcceptTime(), null);
    Date acceptTime2=UtilTool.strToDate(o2.getAcceptTime(), null);
    
    //Date field in ascending order, if you want to use the before method
    if(acceptTime1.after(acceptTime2)) return 1;
    return -1;
  }

}

Three, test,


package junit;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.junit.Test;


public class StepComparatorTest {

  @Test
  public void sort() throws Exception{
    List<Step> steps=new ArrayList<Step>;
    //Sort the collection object
     StepComparator comparator=new StepComparator();
    Collections.sort(steps, comparator);
    if(steps!=null&&steps.size()>0){
      for(Step step:steps){
        System.out.println(step.getAcceptAddress());
        System.out.println(step.getAcceptTime());
      }
    }

  }
}


Related articles: