Java 8 map(),flatMap()示例

使用map()方法

编程时,很常见的是处理数据以便从对象集合中收集一些信息。

假设我们要从特定公司的所有员工中查找城市。 我们的员工班级如下。

public class Employee {
 
    private String name;
    private Integer age;
    private String city;
    private String state; 
    private Department department;
 
    public String getCity() {
         return city;
    }

    public void setCity(String city) {
         this.city = city;
    } 

    public String getState() {
         return state;
    }

    public void setState(String state) {
        this.state = state;
    }
}

我没有包括Employee类的所有属性,但是在这种情况下,我需要的是city属性。

因此,现在,我们有了Employee对象的列表,需要找出不同的城市。 让我们看看Java 8之前的方法。希望,您将编写以下代码来获得不同的城市。

List<Employee> employeeList = .....
Set<String> cities = new HashSet<String>();
for (Employee emp : employeeList) {
    cities.add(emp.getCity());
}

Java 8 Stream接口引入了map()方法,该方法以函数作为参数。 此函数应用于流中的每个元素并返回新流。 该代码将如下所示。

List<Employee> employeeList = new ArrayList<Employee>();
List<String> cities = employeeList.stream()
                                  .map(Employee::getCity)
                                  .distinct()
                                  .collect(Collectors.toList());

使用flatMap()方法

Java 8 Stream接口引入了flatMap()方法,该方法可用于将几个流合并或拼合为单个流。

让我们举个例子。 假设我们想过滤掉文本文件中的不同单词。 查看以下文本文件。

Sri Lanka is a beautiful country in Indian ocean.
It is totally surrounded by the sea.

在Java 8中,我们可以使用一行读取文本文件,它将返回字符串流。 流的每个元素将是文本文件的一行。

Stream<String> lineStream = Files.lines(Paths.get("data.txt"), Charset.defaultCharset());

如果通过打印'lineStream'Stream看到上述代码的输出,则将是文本文件的行。

接下来,我们可以将上述流的每个元素转换为单词流。 然后,我们可以使用flatMap()方法将所有单词流扁平化为单个Stream。 如果我们对lineStream Stream的每个元素执行以下代码,我们将获得两个单词流。 请参阅以下代码。

line -> Arrays.stream(line.split(" "))

两个单词流如下。

Stream 1 : [SriLanka][is][a][beautiful][country][in][Indian][ocean.]} 
Stream 2 : [It][is][totally][surrounded][by][the][sea.]

flatMap()方法可以将这两者平化为单个单词流,如下所示。

Stream<String> wordStream = lineStream.flatMap(line -> Arrays.stream(line.split(" ")));

如果打印上述wordStream的元素,它将是文本文件中的所有单词。 但是,您仍然会看到重复的单词。 您可以使用distinct()方法来避免重复。 这是最终代码。

List<String> wordStream = lineStream.flatMap(line -> Arrays.stream(line.split(" ")))
                                    .distinct()
                                    .collect(Collectors.toList());

如果仔细观察,您只需在Java 8中使用两行代码即可找到文本文件的不同单词。

翻译自: https://www.javacodegeeks.com/2018/07/java-8-map-flatmap-examples.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值