JDK8通过Stream 对List,Map操作和互转的实现
1、Map数据转换为自定义对象的List,例如把map的key,value分别对应Person对象两个属性:
Listlist=map.entrySet().stream().sorted(Comparator.comparing(e->e.getKey())) .map(e->newPerson(e.getKey(),e.getValue())).collect(Collectors.toList()); List list=map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue)) .map(e->newPerson(e.getKey(),e.getValue())).collect(Collectors.toList()); List list=map.entrySet().stream().sorted(Map.Entry.comparingByKey()) .map(e->newPerson(e.getKey(),e.getValue())).collect(Collectors.toList());
以上三种方式不同之处在于排序的处理。参考链接:
https://www.concretepage.com/java/jdk-8/java-8-convert-map-to-list-using-collectors-tolist-example
2、List对象转换为其他List对象:
Listemployees=persons.stream() .filter(p->p.getLastName().equals("l1")) .map(p->newEmployee(p.getName(),p.getLastName(),1000)) .collect(Collectors.toList());
3、从List中过滤出一个元素
Usermatch=users.stream().filter((user)->user.getId()==1).findAny().get();
4、List转换为Map
publicclassHosting{ privateintId; privateStringname; privatelongwebsites; publicHosting(intid,Stringname,longwebsites){ Id=id; this.name=name; this.websites=websites; } //getters,settersandtoString() } Mapresult1=list.stream().collect( Collectors.toMap(Hosting::getId,Hosting::getName));
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。