DEV Community

Code Green
Code Green

Posted on

1

Explain Functional Interfaces and Streams in Java 8

Functional Interfaces and Streams in Java 8


Overview of Streams

Streams are a new abstraction introduced in Java 8 that allow for functional-style operations on collections of elements. They provide a way to process sequences of elements (like lists or sets) in a declarative manner.

Using Functional Interfaces with Streams

Functional interfaces play a crucial role in the Stream API, as they are used to define the behavior of operations such as filtering, mapping, and reducing.

1. Using Predicate with Streams

The filter() method uses a Predicate to determine which elements to include in the resulting stream.

    List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
    List<String> filteredNames = names.stream()
                                          .filter(name -> name.startsWith("A"))
                                          .collect(Collectors.toList());
    System.out.println(filteredNames); // Output: [Alice]
Enter fullscreen mode Exit fullscreen mode

2. Using Function with Streams

The map() method applies a function to each element in the stream, transforming it into another form.

    List<Integer> lengths = names.stream()
                                              .map(String::length)
                                              .collect(Collectors.toList());
    System.out.println(lengths); // Output: [5, 3, 7, 5]
Enter fullscreen mode Exit fullscreen mode

3. Using Consumer with Streams

The forEach() method takes a consumer that defines what to do with each element in the stream.

    names.stream()
         .forEach(name -> System.out.println(name)); // Prints each name
Enter fullscreen mode Exit fullscreen mode

4. Using Supplier with Streams

A supplier can be used to provide initial values for operations like collecting results.

    Supplier<List<String>> listSupplier = ArrayList::new;
    List<String> collectedNames = names.stream()
                                            .filter(name -> name.length() > 3)
                                            .collect(listSupplier, List::add, List::addAll);
    System.out.println(collectedNames); // Output: [Alice, Charlie]
Enter fullscreen mode Exit fullscreen mode

5. Using BinarayOperator with Streams

The reduce() method uses a binary operator to combine elements into a single result.

    Optional<Integer> totalLength = names.stream()
                                                       .map(String::length)
                                                       .reduce(0, Integer::sum);
    System.out.println(totalLength.get()); // Output: 20
Enter fullscreen mode Exit fullscreen mode

Conclusion

The integration of functional interfaces with the Stream API allows developers to write clean and efficient code for processing collections. By leveraging predicates, functions, consumers, suppliers, and binary operators, you can perform complex data manipulations with ease.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more