Java – Arrays.sort custom Comparator example

import java.util.Arrays;
import java.util.Comparator;

public class Main {
  public static void main(String[] args) {
    // Custom Comparator to compare int value of String
    Comparator<String> comparator = new Comparator<String>() {
      @Override
      public int compare(String o1, String o2) {
        return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
      }
    };
    String[] strArr = {"10", "2", "3"};
    System.out.println("Sort outcome without custom Comparator");
    Arrays.sort(strArr);
    for (String str: strArr) {
      System.out.println(str);
    }
    System.out.println("Sort outcome with custom Comparator");
    Arrays.sort(strArr, comparator);
    for (String str: strArr) {
      System.out.println(str);
    }
  }
}
OpenJDK 64-Bit Server VM warning: Insufficient space for shared memory file:
   1768
Try using the -Djava.io.tmpdir= option to select an alternate temp location.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments