forEach用于遍历元素。
List
List employeeList = new ArrayList<>();
employeeList.add(new Employee("Alice", 23, "London", 1200.00));
employeeList.add(new Employee("Bob", 19, "London", 2000.00));
employeeList.add(new Employee("Charles", 25, "New York", 1650.00));
employeeList.add(new Employee("Dorothy", 20, "Hong Kong", 1200.00));
Map
// key - name, value - Employee
Map map1 = employeeList.stream()
.collect(toMap(Employee::getName, Function.identity()));
Person:
public class Person {
private String userName;
private Integer age;
public Person() {
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
例子:
(1)获取所有Employee的name
List names = new ArrayList<>();
employeeList.forEach(employee -> names.add(employee.getName()));
例子:
(1)获取所有Employee的人员信息
List personInfos = new ArrayList<>();
map1.forEach((key, value) -> personInfos.add(key + "/" + value.getAge() + "/" + value.getCity()));
filter用于过滤元素。
例子:
(1)筛选出住在London的Employee
List afterFilter = employeeList.stream()
.filter(employee -> "London".equals(employee.getCity()))
.collect(toList());
filter()、findAny()、orElse()配合使用,可以根据条件获取某个元素,如果没有返回指定的值。
2.2.1 单条件
例子:
(1)找到名字为Alice的任何一个对象,如果不存在返回null
Employee alice = employeeList.stream()
.filter(employee -> "Alice".equals(employee.getName()))
.findAny()
.orElse(null);
2.2.2 多条件
例子:
(1)根据city和age筛选对象
Employee result = employeeList.stream()
.filter(employee -> ("London".equals(employee.getCity()) && employee.getAge() < 20))
.findAny()
.orElse(null);
有时候经过筛选之后,我们想得到的可能不是对象本身,而是对象中的一个属性,可以通过map转换。
例子:
(1)找到名字为Alice的任何一个对象,返回它的属性,如果不存在返回""
String attribute = employeeList.stream()
.filter(employee -> "Alice".equals(employee.getName()))
.map(employee -> (employee.getName() + "/" + employee.getAge() + "/" + employee.getCity()))
.findAny()
.orElse("");
通过map可以将一种类型的对象转换成另一种类型的对象。
(1)小写字母转换为大写字母
List arrayBefore = Arrays.asList("a", "b", "c", "d");
List arrayAfter = arrayBefore.stream()
.map(String::toUpperCase)
.collect(toList());
可以通过map提取对象集合的某个属性集合。
例子:
(1)获取List
List nameList = employeeList.stream()
.map(Employee::getName)
.collect(toList());
例子:
(1)将List
List personList = employeeList.stream()
.map(employee -> {
Person person = new Person();
person.setName(employee.getName());
return person;
})
.collect(toList());