Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Local Development Environments Exploring Your IDE Running Your Code

Brian Bartholomew
Brian Bartholomew
1,741 Points

List.sort() does not exist in Java 7, what other methods could be used?

I am learning java for work. We have legacy software and use Java 7. List.sort() was introduced in Java 8. Hence, my compiling error:

Error:(81, 10) java: cannot find symbol
  symbol:   method sort(<anonymous java.util.Comparator<com.teamtreehouse.model.Song>>)
  location: variable songs of type java.util.List<com.teamtreehouse.model.Song>

I was thinking that refactoring the List to be a Tree of some sort would help the alphabetizing.

Is there a simpler way?

2 Answers

I fixed this using

        List<Song> songs = byArtist().get(artistName);
        Collections.sort(songs,new Comparator<Song>() {


            @Override
            public int compare(Song song1, Song song2) {
                if (song1.equals(song2)) {
                    return 0;
                }
                return song1.mTitle.compareTo(song2.mTitle);
            }
        });

instead of

songs.sort(new Comparator<Song>() {


            @Override
            public int compare(Song song1, Song song2) {
                if (song1.equals(song2)) {
                    return 0;
                }
                return song1.mTitle.compareTo(song2.mTitle);
            }
        });

For earlier versions of Java I think you can use Collections in the java.util package instead.

Collections.sort( myComparableList );

http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html