Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

java - How to sort String array by length using Arrays.sort()

I am trying to sort an array of strings according to their length using Arrays.sort(), but this sorts the strings lexicographically rather than by length. Here is my code:

S = "No one could disentangle correctly"
String W[] = S.split(" ");
Arrays.sort(W);

After sorting :

correctly
could
disentangle
no
one

but what I want is

no  //length = 2
one //length = 3
could //length = 4 and likewise
correctly
disentangle

How can I get the above output? Please give answer for JDK 1.7 & JDK1.8.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For java 8 and above

 Arrays.sort(W, (a, b)->Integer.compare(a.length(), b.length()));

A more concise way is to use Comparator.comparingInt from Mano's answer here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...