Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Locating Elements in Java Lists with Stream API

Tech Apr 22 45

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

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...

Comprehensive Guide to Hive SQL Syntax and Operations

This article provides a detailed walkthrough of Hive SQL, categorizing its features and syntax for practical use. Hive SQL is segmented into the following categories: DDL Statements: Operations on...

Leave a Comment

Anonymous

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