java stream foreach

Deborah 141 Published: 10/31/2024

java stream foreach

Here's an explanation of Java Stream API's foreach method:

In the Java Stream API, foreach is a terminal operation that consumes elements from a stream and executes a provided action for each element. It does not return any value, but simply performs side-effects.

The signature of the foreach method is:

public default void forEach(Consumer action)

Where T is the type of the elements in the stream, and Consumer is a functional interface that represents an operation that accepts a single input argument and returns no value (i.e., a void return).

The foreach method is often used when you need to perform some operation on each element of a stream, but you don't care about the result. It's like a "for-each" loop in traditional programming.

Here are some examples of using foreach:

List names = Arrays.asList("John", "Mary", "Bob");

// Print each name

names.stream()

.forEach(name -> System.out.println(name));

// Print each name with an uppercase first letter

names.stream()

.map(String::toUpperCase)

.forEach(System.out::println);

// Count the number of names that start with 'J'

long count = names.stream()

.filter(name -> name.startsWith("J"))

.peek(System.out::println) // print each matching name

.count();

In these examples, we're using foreach to:

Print each name in the list Print each name in uppercase Count the number of names that start with 'J'

Notice that foreach is a terminal operation, which means it will not allow other operations (like filtering or mapping) to be applied after it. If you try to chain multiple operations together and use foreach at the end, you'll get a compiler error.

Also, keep in mind that foreach does not return any value, so if you need to perform some calculation based on the elements of the stream, you should consider using a different terminal operation like reduce, collect, or count.

java stream map

The power of Java Stream API! map is a fantastic method that allows you to transform the elements of an Stream into another type, and it's extremely useful when working with data transformations.

What does map do?

The map method in Java Stream API applies a given function to each element of a stream, returning a new stream where each element is the result of applying that function. In other words, it takes an input stream, applies some transformation (mapping) to each element, and produces a new output stream.

Example usage

Suppose we have a list of integers representing ages:

List ages = Arrays.asList(25, 30, 35, 20, 40);

We want to create a new stream where each age is replaced with its corresponding string representation (e.g., "Twenty-Five" for 25). We can use the map method to achieve this:

String[] strings = ages.stream()

.map(age -> {

if (age < 30) {

return "Young";

} else if (age >= 40) {

return "Old";

} else {

return "Middle-Aged";

}

})

.toArray(String[]::new);

System.out.println(Arrays.toString(strings));

// Output: [Young, Young, Middle-Aged, Young, Old]

In this example, the map method takes each age and applies a function that returns one of three strings ("Young", "Middle-Aged", or "Old") based on the age value. The resulting stream is then collected into an array of strings.

More examples

Here are some more examples to illustrate the power of map:

Converting strings to uppercase: We can use map to convert all string elements in a stream to uppercase:
List names = Arrays.asList("john", "jane", "bob");

String[] upperCaseNames = names.stream()

.map(String::toUpperCase)

.toArray(String[]::new);

Extracting specific information: Suppose we have a list of objects representing people, and each person has a name and age:
List people = Arrays.asList(

new Person("John", 25),

new Person("Jane", 30),

new Person("Bob", 35)

);

String[] names = people.stream()

.map(person -> person.getName())

.toArray(String[]::new);

In this example, we use map to extract just the name from each person object and collect them into a string array.

Transforming data: We can also use map to perform complex transformations on data. For instance, let's say we have a list of numbers representing temperatures in Celsius:
List temps = Arrays.asList(20.5, 25.2, 30.1);

String[] tempStrings = temps.stream()

.map(temp -> String.format("%.1f°C", temp))

.toArray(String[]::new);

Here, we use map to transform each temperature value into a string representation (e.g., "20.5°C" for 20.5) and collect them into an array of strings.

Conclusion

The map method in Java Stream API is a powerful tool that allows you to transform data streams with ease. By applying a function to each element, you can perform various transformations, such as converting types, extracting specific information, or performing complex calculations. With map, the possibilities are endless!