Sitemap
Nick Lim

Nick Lim

Software Engineer; Java; Spring Boot; jPOS https://github.com/weeshin

Member-only story

10 Java Stream API

4 min readDec 2, 2023

--

Elevate our Java skill set — Java Stream API.

Press enter or click to view image in full size
Photo by Clément Hélardot on Unsplash

Introduction

In this article, we’ll dive into the Java Stream API. The APIs can be complex and challenging to understand. In my experience, i often need to find examples when using them in my programs, especially with those of collectors and reduction functions. To make it easier, I have selected 10 simple and commonly used functions.

1. Stream.collect()

Use the collect() method to get a List from the elements of a stream.

Collectors.toList()

private static final List<String> givenList = Arrays.asList("a", "b", "c");

@Test
public void collectTest() {
final List<String> result = givenList.stream().collect(Collectors.toList());
assertLinesMatch(givenList, result);
}

Collectors.toSet()

Stream<String> setTestStream = Stream.of("a", "b", "c", "b", "d");
Set<String> expectedResult = Set.of("a", "b", "c", "d");

@Test
public void collectSetTest() {
final Set<String> result = setTestStream.collect(Collectors.toSet());
assertEquals(expectedResult.size(), result.size());
}

2. filter()

Filter the expect result by a keyword.

@Test
public void filterTest() {…

--

--