Java Arrays sort using lambda expression as Comparator

Description

Java Arrays sort using lambda expression as Comparator


import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    String[] strings = { "CSS", "Java", "HTML", "css", "sql", "javac", "javascript", "SQL" };

    Arrays.sort(strings, (String s1, String s2) -> {
      int c = s2.length() - s1.length();
      if (c == 0)
        c = s1.compareToIgnoreCase(s2);//from  w ww  .j  a v  a  2s.  c  om
      return c;
    });

    System.out.print(Arrays.toString(strings));
  }
}
import java.util.Arrays;
import java.util.Comparator;

public class Main {
  public static void main(String[] args) {
    Integer[] myArray = { 15, 21, 17, 13, 19 };
    Arrays.sort(myArray, new Comparator<Integer>() {
      @Override/*from w ww.j a  va 2 s . c o  m*/
      public int compare(Integer arg0, Integer arg1) {
        return -1 * arg0.compareTo(arg1);
      }
    });
    System.out.println(Arrays.toString(myArray));
    
    
    Arrays.sort(myArray, (Integer arg0, Integer arg1) ->{
        return -1 * arg0.compareTo(arg1);
    });
    System.out.println(Arrays.toString(myArray));
  }
}



PreviousNext

Related