Map.Entry详解及List的流Stream

Map.Entry详解

Map是java中的接口,Map.Entry是Map的一个内部接口。
Map提供了一些常用方法,如keySet()、entrySet()等方法。
keySet()方法返回值是Map中key值的集合;entrySet()的返回值也是返回一个Set集合,此集合的类型为Map.Entry。
Map.Entry是Map声明的一个内部接口,此接口为泛型,定义为Entry<K,V>。它表示Map中的一个实体(一个key-value对)。接口中有getKey(),getValue方法。

Map<String, String> map = new HashMap<String, String>();    
  map.put("key1", "value1");    
  map.put("key2", "value2");    
  map.put("key3", "value3");    
      
  //第一种:普遍使用,二次取值    
  System.out.println("通过Map.keySet遍历key和value:");    
  for (String key : map.keySet()) {    
   System.out.println("key= "+ key + " and value= " + map.get(key));    
  }    
      
  //第二种    
  System.out.println("通过Map.entrySet使用iterator遍历key和value:");    
  Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();    
  while (it.hasNext()) {    
   Map.Entry<String, String> entry = it.next();    
   System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());    
  }    
      
 //第三种:推荐,尤其是容量大时</span>    
  System.out.println("通过Map.entrySet遍历key和value");    
  for (Map.Entry<String, String> entry : map.entrySet()) {    
   System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());    
  }    
    
  //第四种    
  System.out.println("通过Map.values()遍历所有的value,但不能遍历key");    
  for (String v : map.values()) {    
   System.out.println("value= " + v);    
  }

流Stream

@Data
class UserPo {
    private String name;
    private Integer score;

    public UserPo(String name, Integer score) {
        this.name = name;
        this.score = score;
    }
    public UserPo(String name) {
        this.name = name;
    }
}

public class DateTest{
    public static void main(String[] args) {
        UserPo userPo1 = new UserPo("zhangsan",12);
        UserPo userPo2 = new UserPo("lisi",21);
        UserPo userPo3 = new UserPo("wangwu",43);
        UserPo userPo4 = new UserPo("wangwu111",null);

        /**
         * filter
         * filter:过滤,就是过滤器,符合条件的通过,不符合条件的过滤掉
         * 筛选出成绩不为空的学生人数
         */
        ArrayList<UserPo> list= new ArrayList<>(Arrays.asList(userPo1,userPo2,userPo3));
        long count = list.stream().filter(p -> null != p.getScore()).count();

        /**
         * map:映射,他将原集合映射成为新的集合,在VO、PO处理的过程中较常见。
         * 在本例子中,原集合就是PO集合,新集合可以自定义映射为成绩集合,同时也可以对新集合进行相关操作。
         * 取出所有学生的成绩
         */
        List<Integer> scoreList = list.stream().map(p -> p.getScore()).collect(Collectors.toList());
        // 将学生姓名集合串成字符串,用逗号分隔
        String nameString = list.stream().map(p -> p.getName()).collect(Collectors.joining(","));

        /**
         * sorted:排序,可以根据指定的字段进行排序
         */
        // 按学生成绩逆序排序 正序则不需要加.reversed()
        List<UserPo>  filterList = list.stream().filter(p -> null != p.getScore()).sorted(Comparator.comparing(UserPo::getScore).reversed()).collect(Collectors.toList());

        /**
         * forEach
         * forEach:这个应该是最常用的,也就是为每一个元素进行自定义操作
         * 除了forEach操作会改变原集合的数据,其他的操作均不会改变原集合,这点务必引起注意
         */
        // 学生成绩太差了,及格率太低,给每个学生加10分,放个水
        filterList.stream().forEach(p -> p.setScore(p.getScore() + 10));

        /**
         * collect:聚合,可以用于GroudBy按指定字段分类,也可以用于返回列表或者拼凑字符串
         */
        // 按成绩进行归集
        Map<Integer, List<UserPo>> groupByScoreMap = list.stream().filter(p -> null != p.getScore()).collect(Collectors.groupingBy(UserPo::getScore));
        for (Map.Entry<Integer, List<UserPo>> entry : groupByScoreMap.entrySet()) {
            System.out.println("成绩:" + entry.getKey() + " 人数:" + entry.getValue().size());
        }
        // 返回list
        List<Integer> newScoreList = list.stream().map(p -> p.getScore()).collect(Collectors.toList());
        // 返回string用逗号分隔
        String newNameString = list.stream().map(p -> p.getName()).collect(Collectors.joining(","));
    }
}

stream map使用

@Data
@NoArgsConstructor
@AllArgsConstructor
class User{
    int id;
    String name;
    String address;
}

public class TesStream {
    public static void main(String[] args)  {
        List<User> userList = getUserList () ;
        List<User>  userList1 =  userList.stream().map(user -> {
            User user1 = new User();
            user1.setName("fuzhi");
            user1.setAddress(user.getAddress());
            user1.setId(user.getId());
            return user1;
        }).collect(Collectors.toList());
        System.out.println(userList.toString());
        System.out.println(userList1.toString());

    }
    private static List<User> getUserList (){
        List<User> userList = new ArrayList<>() ;
        userList.add(new User(1,"张三","上海")) ;
        userList.add(new User(2,"李四","北京")) ;
        userList.add(new User(3,"王五","北京")) ;
        userList.add(new User(4,"顺六","上海,杭州")) ;
        return userList ;
    }

}
posted @ 2022-10-11 19:59  离人怎挽_wdj  阅读(338)  评论(0编辑  收藏  举报