list=new..._stream.foreach">
赞
踩
1.map 映射,将流中的每一个元素 T 映射为 R(类似类型转换)
- public class ListToMap {
- public static void main(String[] args) {
- Student stu=new Student();
- stu.setName("ljf");
- stu.setAge(23);
- List<Student> list=new ArrayList<>();
- list.add(stu);
- list.stream().map((e)->{ return e.getName();}).forEach((x)->{System.out.println("x:"+x);});
- }
- }
执行结果:
- public class ListToMap {
- public static void main(String[] args) {
- Student stu=new Student();
- stu.setName("ljf");
- stu.setAge(23);
- List<Student> list=new ArrayList<>();
- list.add(stu);
- //list.stream().map((e)->{ return e.getName();}).forEach((x)->{System.out.println("x:"+x);});
- // list.stream().map((e)->{ return "nihao:";}).collect(Collectors.toList());
- List<String> strList= list.stream().map(e -> "nihao:"+e.getName()).collect(Collectors.toList());
- System.out.println("str:"+strList.toString());
-
- }
- public static List<String> show(List<Student> list){
- return list.stream().map(e -> String.format("haoren")).collect(Collectors.toList());
-
- }
- }
执行结果
- //程序逻辑,将List<Map> list 中的数据遍历存储到List<Map> demoList中。
- Map<String,String> mapStr=new HashMap<String,String>();
- mapStr.put("beijing","001");
- mapStr.put("tianjing","002");
- List<Map> list=new ArrayList<Map>();
- list.add(mapStr);
- //demoList的定义
- List<Map> demoList=new ArrayList<Map>();
- list.stream().forEach(x->{
- System.out.println("x:"+x);
- System.out.println("name:"+x.get("tianjing"));
- //遍历旧list集合中的map元素存储到新map中
- Map<String,String> mapStr2=new HashMap<String,String>() {
- {
- put(x.get("tianjing")+"","天津");
- }
- };
- //将新map存储到新list集合中
- demoList.add(mapStr2);
- });
- //在新集合中进行遍历
- System.out.println("demoList:"+demoList);
- }
程序执行结果:
1.代码
- List<String> oldList = new ArrayList<>();
- oldList.add("beijing");
- oldList.add("shanghai");
- String s="beijing";
- String dList=(String)Arrays.stream(oldList.toArray()).filter(x-> x.equals(s)).findFirst().orElse("");
- System.out.println("d:"+dList.toString());
2.执行结果
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。