Skip to content
Arul Dhesiaseelan edited this page Feb 5, 2014 · 37 revisions

10 Java One Liners to Impress Your Friends

Here is my take using Java 8: http://mkaz.com/solog/scala/10-scala-one-liners-to-impress-your-friends.html.

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

    final Stream<String> keywords = Stream.of("brown", "fox", "dog", "pangram");
    final String tweet = "The quick brown fox jumps over a lazy dog. #pangram http://www.rinkworks.com/words/pangrams.shtml";

    keywords.anyMatch(tweet::contains);
    keywords.reduce(false, (b, keyword) -> b || tweet.contains(keyword), (l, r) -> l || r);

4. Read in a File^

    try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
      String fileText = reader.lines().reduce("", String::concat);
    }

    try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
      List<String> fileLines = reader.lines().collect(toCollection(LinkedList<String>::new));
    }

    try (Stream<String> lines = Files.lines(new File("data.txt").toPath(), Charset.defaultCharset())) {
      List<String> fileLines = lines.collect(toCollection(LinkedList<String>::new));
    }

5. Happy Birthday to You!

    range(1, 5).boxed().map(i -> { out.print("Happy Birthday "); if (i == 3) return "dear NAME"; else return "to You"; }).forEach(out::println);

6. Filter list of numbers

    Map<String, List<Integer>> result = Stream.of(49, 58, 76, 82, 88, 90).collect(groupingBy(forPredicate(i -> i > 60, "passed", "failed")));

7. Fetch and Parse an XML web service^^

    FeedType feed = JAXB.unmarshal(new URL("http://search.twitter.com/search.atom?&q=java8"), FeedType.class);
    JAXB.marshal(feed, System.out);

8. Find minimum (or maximum) in a List

    int min = Stream.of(14, 35, -7, 46, 98).reduce(Integer::min).get();
    min = Stream.of(14, 35, -7, 46, 98).min(Integer::compare).get();

    int max = Stream.of(14, 35, -7, 46, 98).reduce(Integer::max).get();
    max = Stream.of(14, 35, -7, 46, 98).max(Integer::compare).get();

9. Parallel Processing

    long result = dataList.parallelStream().mapToInt(line -> processItem(line)).sum();

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 albums
    List<Track> allTracks = albums.stream()
      .flatMap(album -> album.tracks.stream())
      .collect(toList());

    // Group album tracks by rating
    Map<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.

Clone this wiki locally