Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting strings in Java based on substrings [closed]

I have a list of strings def123, abc999, zzz000, abc123, zzz111. I want the list sorted such that first three characters are sorted in ascendng order and next three in descending. So the output should be abc999, abc123, def123, zzz111,zzz000 Is this possible?

like image 696
Tejashwini Avatar asked Dec 24 '22 01:12

Tejashwini


2 Answers

Other answers have suggested you implement Comparator. That's no longer necessary with recent utility methods added to the interface in Java 8:

list.sort(Comparator
    .comparing(s -> s.substring(0, 3))
    .thenComparing(s -> s.subtring(3, 6), Comparator.reverseOrder()));

Also note that List now has a sort method.

like image 90
sprinter Avatar answered Dec 28 '22 06:12

sprinter


Yes, it is possible. You will have to write your own Comparator. Here's a tutorial to get you started https://www.tutorialspoint.com//java/java_using_comparator.htm

like image 35
Sharon Ben Asher Avatar answered Dec 28 '22 06:12

Sharon Ben Asher