Collections and streams

Categories: Java

An interesting way to process a collection is the usage of streams. A stream provides a sequential access to the elements of the collection. Below a code snipped for a simple selection of elements of an existing collection.

In this example the dataList contains just some Strings and we want to get a new list of all Strings, that contain a specific char sequence.

List<String> myFancyList = dataList
.stream()
.filter(e -> e.contains("whatever"))
.collect(Collectors.toList());

Well, thats just an easy example, you will definitely find a more worthful usage in your projects 😉

It’s getting a little bit more tricky, if you want to get a list with different types. Eg. if you want to select by a filter condition and want all the matching elements converted to a different type. Therefore the forEach method is quite usable:

List<CustomerDto> customerList = oldCustomerList.getCustomers()
.stream()
.filter(e -> e.getAmount() > 1000)
.forEach(mapOld2New(e, operatorId));

Every element that matches the filter criteria (in this case amount larger than 1000) will be processed by a mapping method (mapOld2New) where some data conversion to type CustomerDto is done and additional the actual operatorId (that is set some lines before this stream operation is invoked) is added to the new CustomerDto.

«

    Leave a Reply

    Your email address will not be published. Required fields are marked *