本文共 1468 字,大约阅读时间需要 4 分钟。
定义一个对象
public Class Person{ private Long id; private String userName; // ... 省略get和set方法 }
在List中,查找userName为”alex”的对象alex。
OptionalfirstPerson= 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 { //没有查到的逻辑}
ListfirstA= AList.stream() .filter(a -> "alex".equals(a.getUserName())) .collect(Collectors.toList());
ListidList = AList.stream .map(Person::getId) .collect(Collectors.toList());
迭代的时候不能改变集合的结构,例如不能调用add(),remove()
转换数组为List
1.使用Stream中的Collector收集器,代码:
String[] arrays = new String[]{ "a", "b", "c"}; ListlistStrings = Stream.of(arrays).collector(Collectors.toList());
String[] arrays = new String[]{ "a", "b", "c"}; ListlistStrings = Arrays.asList(arrays);
转换List为数组
1. 使用Stream:[java] view plain copyString[] ss = listStrings.stream().toArray(String[]::new);
String[] sss = listStrings.toArray(new String[listStrings.size()]);
转载地址:http://deqab.baihongyu.com/