You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I am replacing Sieve of Eratosthenes with LINQ style builder as the former is technically not a one-liner in Scala.
1. Multiple Each Item in a List by 2
// Range is half-open (exclusive) in Java, unlike Scala.int[] ia = range(1, 10).map(i -> i * 2).toArray();
List<Integer> result = range(1, 10).map(i -> i * 2).boxed().collect(toList());
2. Sum a List of Numbers
range(1, 1000).sum();
range(1, 1000).reduce(0, Integer::sum);
Stream.iterate(0, i -> i + 1).limit(1000).reduce(0, Integer::sum);
IntStream.iterate(0, i -> i + 1).limit(1000).reduce(0, Integer::sum);
3. Verify if Exists in a String
finalList<String> keywords = Arrays.asList("brown", "fox", "dog", "pangram");
finalStringtweet = "The quick brown fox jumps over a lazy dog. #pangram http://www.rinkworks.com/words/pangrams.shtml";
keywords.stream().anyMatch(tweet::contains);
keywords.stream().reduce(false, (b, keyword) -> b || tweet.contains(keyword), (l, r) -> l || r);
10. Ad-hoc queries over collections (LINQ in Java)
List<Album> albums = Arrays.asList(unapologetic, tailgates, red);
// 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.name))
.forEach(album -> System.out.println(album.name));
// Merge tracks from all albumsList<Track> allTracks = albums.stream()
.flatMap(album -> album.tracks.stream())
.collect(toList());
// Group album tracks by ratingMap<Integer, List<Track>> tracksByRating = allTracks.stream()
.collect(groupingBy(Track::getRating));
###Note:
^ I would still consider Try With Resources construct a one-liner.
^^ This is the odd man out that does not use Java 8 construct, although it is super simple with Java for years with the help of JAXB.