stream ,filter 等功能代替for循环
定义一个对象
public Class Person{
private Long id;
private String userName;
// ... 省略get和set方法
}
在List中,查找userName为”alex”的对象alex。
- 查找集合中的第一个对象。
Optional<Person> firstPerson= AList.stream()
.filter(a -> "alex".equals(a.getUserName()))
.findFirst();
关于Optional,java API中给了解释: A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.
if (firstPerson.isPresent()) {
Person person = firstPerson.get(); //这样子就取到了这个对象
}
else {
//没有查到的逻辑
}
- 如果想返回集合呢。可是使用这个
List<Person> firstA= AList.stream()
.filter(a -> "alex".equals(a.getUserName()))
.collect(Collectors.toList());
- 抽取对象中所有的id的集合
List<Long> idList = AList.stream
.map(Person::getId)
.collect(Collectors.toList());
迭代器
迭代的时候不能改变集合的结构,例如不能调用add(),remove()
深入理解迭代器
https://blog.csdn.net/zhaokejin521
List和数组转换
转换数组为List
1.使用Stream中的Collector收集器,代码:
String[] arrays = new String[]{"a", "b", "c"};
List<String> listStrings = Stream.of(arrays).collector(Collectors.toList());
- 使用java.util.Arrays工具类中的asList()方法(这个不是Java8中新增的内容):
String[] arrays = new String[]{"a", "b", "c"};
List<String> listStrings = Arrays.asList(arrays);
转换List为数组
1. 使用Stream:
[java] view plain copy
String[] ss = listStrings.stream().toArray(String[]::new);
- 使用List中的toArray()方法
String[] sss = listStrings.toArray(new String[listStrings.size()]);