10 Java One‑Liners Using Lambda and Stream for Common Tasks
This article presents ten concise Java 8 one‑liners that leverage lambda expressions, streams, try‑with‑resources, and other modern features to perform common operations such as mapping, summing, filtering, file I/O, XML parsing, min/max calculations, parallel processing, and LINQ‑style queries in a single line of code.
The article lists ten independent Java one‑liners that demonstrate how Java 8 features like lambda expressions, streams, try‑with‑resources, and JAXB can be used to implement common business logic without relying on additional code.
1. Multiply each element in a list/array by 2 int[] ia = range(1, 10).map(i -> i * 2).toArray(); List result = range(1, 10).map(i -> i * 2).boxed().collect(toList());
2. Compute the sum of numbers in a collection/array 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. Check whether a string contains any keyword from a collection final List keywords = Arrays.asList("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.stream().anyMatch(tweet::contains); keywords.stream().reduce(false, (b, keyword) -> b || tweet.contains(keyword), (l, r) -> l || r);
4. Read file content (try‑with‑resources) 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 fileLines = reader.lines().collect(toCollection(LinkedList::new)); } try (Stream lines = Files.lines(new File("data.txt").toPath(), Charset.defaultCharset())) { List fileLines = lines.collect(toCollection(LinkedList::new)); }
5. Print the "Happy Birthday" song with conditional text 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 and group numbers in a collection Map > result = Stream.of(49, 58, 76, 82, 88, 90) .collect(groupingBy(forPredicate(i -> i > 60, "passed", "failed")));
7. Retrieve and marshal an XML Web Service using JAXB FeedType feed = JAXB.unmarshal(new URL("http://search.twitter.com/search.atom?&q=java8"), FeedType.class); JAXB.marshal(feed, System.out);
8. Obtain the minimum and maximum numbers in a collection 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(); min = Stream.of(14, 35, -7, 46, 98).mapToInt(Integer::new).min(); 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(); max = Stream.of(14, 35, -7, 46, 98).mapToInt(Integer::new).max();
9. Parallel processing long result = dataList.parallelStream().mapToInt(line -> processItem(line)).sum();
10. Various queries on collections (LINQ‑style in Java) List albums = Arrays.asList(unapologetic, tailgates, red); // Filter albums with at least one track rating >= 4, sort by name, and print 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 all tracks from all albums List allTracks = albums.stream() .flatMap(album -> album.tracks.stream()) .collect(toList()); // Group tracks by rating Map > tracksByRating = allTracks.stream() .collect(groupingBy(Track::getRating));
Source: rowkey.me/blog/2017/09/09/java-oneliners/
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.