Java Stream flatMap()

Java Stream flatMap() is a very useful function to flatten the Stream after applying the given function to all the elements of the stream.

在将给定函数应用于流的所有元素之后, Java Stream flatMap()是一个非常有用的函数,用于将Stream扁平化。

Java Stream flatMap (Java Stream flatMap)

Let’s look at the syntax of Stream flatMap() function.

让我们看一下Stream flatMap()函数的语法。

<R> Stream<R> flatMap(Function<T, Stream<R>> mapper);

In simple words, flatMap() is used when we have a stream of collections and we want to flatten it rather than using map() function and getting the nested Stream.

简而言之,当我们有一个集合流并且想要对其进行展平而不是使用map()函数并获取嵌套的Stream时,将使用flatMap()。

Let’s look at an example to better understand this scenario. Suppose we have few List of Strings:

让我们看一个示例,以更好地理解这种情况。 假设我们有几个字符串列表:

List<String> l1 = Arrays.asList("a","b");
List<String> l2 = Arrays.asList("c","d");

Now we want to merge these lists and get a new list of Strings and change the letters to uppercase. Since we have multiple lists, we will have to first merge them to a single list and then apply map() function. Something like below code:

现在,我们要合并这些列表,并获得一个新的字符串列表,并将字母更改为大写。 由于我们有多个列表,因此我们必须首先将它们合并到一个列表中,然后再应用map()函数。 类似于以下代码:

List<String> l = new ArrayList<>();
l.addAll(l1);
l.addAll(l2);

List<String> letters = l.stream()
			.map(String::toUpperCase)
			.collect(Collectors.toList());

Obviously this is a lot of rework and we have to manually merge the lists to get a single list of elements and then apply map() function. This is where flatMap() is very useful. Let’s see how we can use flatMap() to perform the same operation.

显然,这需要大量的工作,我们必须手动合并列表以获取单个元素列表,然后应用map()函数。 这是flatMap()非常有用的地方。 让我们看看如何使用flatMap()执行相同的操作。

List<String> betterLetters = Stream.of(l1, l2)
				.flatMap(List::stream)
				.map(String::toUpperCase)
				.collect(Collectors.toList());

Now it’s clear that we used flatMap() function to flatten the Stream of Lists to Stream of elements.

现在很明显,我们使用了flatMap()函数将列表流展平为元素流。

Java Stream flatMap()实际示例 (Java Stream flatMap() Real Life Example)

Let’s look into a real life example where flatMap() function will be really helpful. Suppose we have a State class that contains list of cities. Now we have a list of States and we want to get the list of all the cities. Here flatMap() will be very helpful as we won’t have to write nested for loops and iterate over the lists manually. Below is a complete example to show this scenario.

让我们看一个真实的例子,其中flatMap()函数将非常有用。 假设我们有一个State类,其中包含城市列表。 现在我们有了州列表,我们希望获得所有城市的列表。 在这里,flatMap()将非常有帮助,因为我们不必编写嵌套的for循环并手动遍历列表。 下面是显示此方案的完整示例。

package com.journaldev.streams;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class JavaStreamFlatMapAggregateExample {
	public static void main(String[] args) {
		State karnataka = new State();
		karnataka.addCity("Bangalore");
		karnataka.addCity("Mysore");

		State punjab = new State();
		punjab.addCity("Chandigarh");
		punjab.addCity("Ludhiana");

		List<State> allStates = Arrays.asList(karnataka, punjab);

		//Java Stream flatMap way
		List<String> allCities = allStates.stream().flatMap(e -> e.getCities().stream()).collect(Collectors.toList());
		
		System.out.println(allCities);
		
		//legacy way
		allCities = new ArrayList<String>();
		for(State state : allStates) {
			for(String city : state.getCities())
				allCities.add(city);
		}
		System.out.println(allCities);
	}

}

class State {
	private List<String> cities = new ArrayList<>();

	public void addCity(String city) {
		cities.add(city);
	}

	public List<String> getCities() {
		return this.cities;
	}
}

It’s very clear that flatMap() is very useful when we have to work with List of lists.

很明显,当我们必须使用列表列表时,flatMap()非常有用。

GitHub Repository. GitHub Repository下载示例代码。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/20775/java-stream-flatmap

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值