Skip to content

Instantly share code, notes, and snippets.

@aruld
Created March 31, 2013 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aruld/5282302 to your computer and use it in GitHub Desktop.
Save aruld/5282302 to your computer and use it in GitHub Desktop.
Ad-hoc queries over collections (LINQ in Java) https://github.com/aruld/java-oneliners
// Print the names of albums that have at least one track rated four or higher, sorted by name.
albums.stream()
.filter(a -> a.tracks.stream().anyMatch(t -> (t.rating >= 4)))
.sorted(comparing((Album album) -> album.name))
.forEach(album -> System.out.println(album.name));
// Merge tracks from all albums
List<Track> allTracks = albums.stream()
.flatMap((Album album) -> album.tracks.stream())
.collect(toList());
// Group album tracks by rating
Map<Integer, List<Track>> tracksByRating = allTracks.stream()
.collect(groupingBy(Track::getRating));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment