10 Java One‑Liners Using Lambda, Stream, and Try‑with‑Resources
This article presents ten independent Java 8 one‑liner examples that demonstrate how to perform common tasks such as mapping, summing, string matching, file reading, conditional output, grouping, XML parsing, min/max calculations, parallel processing, and LINQ‑style queries using Lambda, Stream, try‑with‑resources and related APIs.
This article lists ten business‑logic snippets that can be written as a single independent line of Java code, primarily leveraging Java 8 features such as Lambda expressions, the Stream API, try‑with‑resources, JAXB, and other utilities.
1. Multiply each element in a list/array by 2
// Range is half‑open interval
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 (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. Output the song "Happy Birthday to You!" – different strings for different elements
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 parse an XML‑based Web Service
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/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 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));These snippets illustrate how Java 8’s functional features can dramatically reduce boilerplate and enable concise, expressive solutions for everyday programming tasks.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.