Skip to content

Instantly share code, notes, and snippets.

@RICH0423
Last active January 24, 2018 02:20
Show Gist options
  • Save RICH0423/b3706a10e595637a07f3934db501dc1d to your computer and use it in GitHub Desktop.
Save RICH0423/b3706a10e595637a07f3934db501dc1d to your computer and use it in GitHub Desktop.
Sorting with JDK 8 Comparator interface
import static java.lang.System.out;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
private static List<Song> generateSongs() {
final ArrayList<Song> songs = new ArrayList<>();
songs.add(
new Song(
"Photograph",
"Pyromania",
"Def Leppard",
1983));
songs.add(
new Song(
"Hysteria",
"Hysteria",
"Def Leppard",
1987));
songs.add(
new Song(
"Shout",
"Songs from the Big Chair",
"Tears for Fears",
1984));
songs.add(
new Song(
"Everybody Wants to Rule the World",
"Songs from the Big Chair",
"Tears for Fears",
1985));
songs.add(
new Song(
"Head Over Heels",
"Songs from the Big Chair",
"Tears for Fears",
1985
));
songs.add(
new Song(
"Enter Sandman",
"Metallica",
"Metallica",
1991
)
);
songs.add(
new Song(
"Money for Nothing",
"Brothers in Arms",
"Dire Straits",
1985
)
);
songs.add(
new Song(
"Don't You (Forget About Me)",
"A Brass Band in African Chimes",
"Simple Minds",
1985
)
);
return songs;
}
/**
* Returns a sorted version of the provided List of Songs that is
* sorted first by year of song's release, then sorted by artist,
* and then sorted by album.
*
* @param songsToSort Songs to be sorted.
* @return Songs sorted, in this order, by year, artist, and album.
*/
private static List<Song> sortedSongsByYearArtistAlbum(
final List<Song> songsToSort) {
return songsToSort.stream()
.sorted(
Comparator.comparingInt(Song::getYear)
.thenComparing(Song::getArtist)
.thenComparing(Song::getAlbum))
.collect(Collectors.toList());
}
public static void main(final String[] arguments) {
final List<Song> songs = generateSongs();
final List<Song> sortedSongs = sortedSongsByYearArtistAlbum(songs);
out.println("Original Songs:");
songs.stream().forEach(song -> out.println("\t" + song));
out.println("Sorted Songs");
sortedSongs.forEach(song -> out.println("\t" + song));
}
}
public class Song {
private final String title;
private final String album;
private final String artist;
private final int year;
public Song(final String newTitle, final String newAlbum,
final String newArtist, final int newYear) {
title = newTitle;
album = newAlbum;
artist = newArtist;
year = newYear;
}
public String getTitle()
{
return title;
}
public String getAlbum()
{
return album;
}
public String getArtist()
{
return artist;
}
public int getYear()
{
return year;
}
@Override
public String toString() {
return "'" + title + "' (" + year + ") from '" + album + "' by " + artist;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment