个人可以做导航网站吗,网站开发如何引用函数,风兰网络,安全协议书 网站开发公司使用map#xff08;#xff09;方法 编程时#xff0c;很常见的是处理数据以便从对象集合中收集一些信息。 假设我们要从特定公司的所有员工中查找城市。 我们的员工班级如下。 public class Employee {private String name;private Integer age;private String city;priv… 使用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之前的方法。希望您将编写以下代码来获得不同的城市。 ListEmployee employeeList .....
SetString cities new HashSetString();
for (Employee emp : employeeList) {cities.add(emp.getCity());
} Java 8 Stream接口引入了map()方法该方法以函数作为参数。 此函数应用于流中的每个元素并返回新流。 该代码将如下所示。 ListEmployee employeeList new ArrayListEmployee();
ListString 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中我们可以使用一行读取文本文件它将返回字符串流。 流的每个元素将是文本文件的一行。 StreamString lineStream Files.lines(Paths.get(data.txt), Charset.defaultCharset()); 如果通过打印lineStreamStream看到上述代码的输出则将是文本文件的行。 接下来我们可以将上述流的每个元素转换为单词流。 然后我们可以使用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()方法可以将这两者平化为单个单词流如下所示。 StreamString wordStream lineStream.flatMap(line - Arrays.stream(line.split( ))); 如果打印上述wordStream的元素它将是文本文件中的所有单词。 但是您仍然会看到重复的单词。 您可以使用distinct()方法来避免重复。 这是最终代码。 ListString 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