I have such a strange task: it is necessary to sort the array of strings by increasing their length, and using Arrays.sort (arr), moreover. I did a sorting by loops, but I was told that sort () was needed, but it had no overload with a String. There is only a strange garbage

public static <T> void sort(T[] a, Comparator<? super T> c) 

I guess she needs it, but I don’t understand how it works ... Explain what it means:

 <T> 

and

 Comparator<? super T> 

What is T ?

  • T - type of elements; Comparator - a function producing a comparison, on the basis of which the order of elements is determined - Grundy

1 answer 1

Class where we determine the order of comparison:

 class StringLengthSort implements Comparator<String>{ @Override public int compare(String o1, String o2) { if(o1.length() > o2.length()){ return 1; }else{ if(o1.length() < o2.length()){ return -1; }else{ return 0; } } } } 

or through lambda, the code will be slightly shorter:

 Comparator<String> comprator = (o1,o2) -> o1.length() - o2.length(); 

Testing:

 public static void main(String[] args) { String [] names = {"Deaaaaaaan", "Deaaan", "Deaaaaaaaan", "Dean", "Deaaaaaan", "Deaan", "Deaaaaaaaaan", "Deaaaan", "Deaaaaan"}; Comparator<String> stringLengthComparator = new StringLengthSort(); for(String str : names){ System.out.println(str); } Arrays.sort(names, stringLengthComparator); // применяем сортировку System.out.println("\nотсортировано\n"); for(String str : names){ System.out.println(str); } } 

Conclusion:

 Deaaaaaaan Deaaan Deaaaaaaaan Dean Deaaaaaan Deaan Deaaaaaaaaan Deaaaan Deaaaaan отсортировано Dean Deaan Deaaan Deaaaan Deaaaaan Deaaaaaan Deaaaaaaan Deaaaaaaaan Deaaaaaaaaan 
  • Comparators will save the world :) - Flippy
  • Thank you very much! And please tell me how this line is read in Russian here (o1, o2) -> o1.length () - o2.length () - Pavel
  • Ie what does this pipka ->? ))) Stay for Moveton))) - Pavel
  • This is a lambda expression - user31238
  • @Pavel, this is a lambda expression, if simpler - an anonymous method. - Pollux