Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Locating Elements in Java Lists with Stream API

Tech 1

Traditional approaches for querying collectinos, such as contains or indexOf, are limited to exact matches. Java 8 introduced the Stream API, enabling expressive and flexible querying capabilities.

Retrieving a Single Matching Element

To locate a specific item based on a condition, combine filter with findFirst or findAny. The filter operation isolates matching elements, while findFirst retrieves the initial occurrence wrapped in a Optional.

List<Integer> values = Arrays.asList(5, 12, 7, 20, 15);
Optional<Integer> match = values.stream()
    .filter(val -> val > 10)
    .findFirst();

match.ifPresent(res -> System.out.println("First match found: " + res));

Validating Element Existence

When the requirement is solely to verify whether at least one element satisfies a predicate, anyMatch provides a concise solution. It evaluates the pipeline and returns true immediately upon finding a match.

boolean containsNegative = values.stream()
    .anyMatch(val -> val < 0);

System.out.println("Negative value present: " + containsNegative);

Aggregating All Matches

Rather than extracting a single item, extracting all elements that fulfill specific criteria into a new collection is a common pattern. The collect method combined with Collectors.toList() aggregates the filtered results.

List<Integer> evenNumbers = values.stream()
    .filter(val -> val % 2 == 0)
    .collect(Collectors.toList());

System.out.println("Even values: " + evenNumbers);

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.