10 Powerful Java One‑Liners to Simplify Your Code

This article showcases ten concise Java one‑liners that use Java 8 features such as Lambda, Stream, try‑with‑resources, and JAXB to perform common tasks like mapping, summing, filtering, file I/O, XML parsing, and parallel processing without any additional code.

Programmer DD
Programmer DD
Programmer DD
10 Powerful Java One‑Liners to Simplify Your Code

This article lists ten Java one‑liners that perform common tasks without relying on additional code, leveraging Java 8 features such as Lambda, Stream, try‑with‑resources, JAXB, and others.

1. Multiply each element in a list/array by 2

int[] ia = range(1, 10).map(i -> i * 2).toArray();
List<Integer> 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<String> 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 using 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<String> fileLines = reader.lines().collect(toCollection(LinkedList::new));
}
try (Stream<String> lines = Files.lines(new File("data.txt").toPath(), Charset.defaultCharset())) {
    List<String> fileLines = lines.collect(toCollection(LinkedList::new));
}

5. Print the song "Happy Birthday to You!" based on collection 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<String, List<Integer>> result = Stream.of(49, 58, 76, 82, 88, 90)
    .collect(groupingBy(forPredicate(i -> i > 60, "passed", "failed")));

7. Retrieve and marshal 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. Find the minimum and maximum numbers in a collection

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

9. Parallel processing of a list

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

10. Various queries on collections (LINQ‑style in Java)

List<Album> albums = Arrays.asList(unapologetic, tailgates, red);
albums.stream()
    .filter(a -> a.tracks.stream().anyMatch(t -> t.rating >= 4))
    .sorted(comparing(album -> album.name))
    .forEach(album -> System.out.println(album.name));

List<Track> allTracks = albums.stream()
    .flatMap(album -> album.tracks.stream())
    .collect(toList());

Map<Integer, List<Track>> tracksByRating = allTracks.stream()
    .collect(groupingBy(Track::getRating));
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaLambdaStreamsJava8code snippetsOne-liners
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.