How can I call a method on each element of a List?

前端 未结 6 1102
太阳男子
太阳男子 2020-12-09 14:41

Suppose that I have a list of cars :

public class Car {
    private String brand;
    private String name;
    private String color;

    public Car() { // .         


        
6条回答
  •  忘掉有多难
    2020-12-09 15:14

    Better stay away from Guava's Lists.transform unless you are aware what it is doing. Check out this snippet:

    public class User {
        private Integer id;
        // constructor, getters & setters
    }
    
    public class UserDto {
        private Integer id;
        private boolean processed;
    
        public UserDto(User user) {
            this.id = user.getId();
            this.processed = false;
        }
       // getters & setters
    }
    
    // now let's do actual transformation ...
    private List getUsers() {
        List users = List.of(new User(1), new User(2));
        List userDtos = Lists.transform(users, UserDto::new);
        userDtos.forEach(userDto -> userDto.setProcessed(true));
        return userDtos;
    }
    

    You would probably expect processed flag to be set to true for all DTOs, yet this does not happen. While this is the consequence of their "lazy view" approach, it is still quite surprising.

提交回复
热议问题