Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Arrays Gotchas and Wins Sorting

How do I compare by multiple things, such as length first and then the normal lexical string compare?

So, if I want to sort multiple strings, and many of them all have the same length, then I want them to be sorted alphabetically; how do I do that?

1 Answer

Hey Oindril! I was curious about this too. It looks like Java 8 added the thenComparing() method to the Comparator class. If you wanted to sort an array by length of strings and then alphabetically, you could use the following sort call: (say we're working with the friends array described in this lesson)

Arrays.sort(friends, Comparator.comparing(String::length).thenComparing(String::compareTo))

This thenComparing() method takes the same input as the comparing() method. Further, you can add these thenComparing() calls ad nauseam.

Arrays.sort(ARRAY, Comparator.comparing(FIRST).thenComparing(SECOND).thenComparing(Third)...)

If you're working on an earlier version, I've seen post about creating a custom Comparator classes, but that's more advanced than this course.

Hope this helps!