Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Java8将字符串列表转换为对象列表_Java_Stream - Fatal编程技术网

使用Java8将字符串列表转换为对象列表

使用Java8将字符串列表转换为对象列表,java,stream,Java,Stream,有一个从文件中读取的流,每行的内容如下: {"uid":"5981865218","timestamp":1525309552069,"isHot":true} 用户类别: public class User { private String uid; private long timestamp; private boolean isHot; public String getUid() { return uid; } p

有一个从文件中读取的流,每行的内容如下:

 {"uid":"5981865218","timestamp":1525309552069,"isHot":true}
用户类别:

public class User {
    private String uid;
    private long timestamp;
    private boolean isHot;

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    public boolean getIsHot() {
        return isHot;
    }

    public void setIsHot(boolean isHot) {
        this.isHot = isHot;
    }
}
我希望从文件流中获取对象“列表”列表的代码:

BufferedReader targetBr = null;
targetBr = new BufferedReader(new FileReader(targetUsersFile));
List<User> tmpUsers = targetBr.lines().?I don't know how process in there?.collect(Collectors.toList());
BufferedReader targetBr=null;
targetBr=new BufferedReader(new FileReader(targetUsersFile));
列出tmpUsers=targetBr.lines()。?我不知道在那里如何处理?.collect(Collectors.toList());

您需要将字符串反序列化为
User
对象。我在这里用过杰克逊(你也可以用像格森这样的人)

流的
映射
部分使用
函数
,因此您不能从那里抛出选中的异常。因此,我将Jackson
readValue
抛出(可能抛出)的
IOException
包装成一个RuntimeException。您可能需要根据需要更改该部分

这只是一个开始。考虑当存在无法反序列化为
用户的无效条目时该怎么办。一些特殊的情况:

  • 如果输入字符串中存在无法识别的字段(用户类中不存在的属性),该怎么办。在这种情况下,ObjectMapper抛出一个
    无法识别的属性异常
    异常。你可以找到忽略它的方法
  • 如果用户类中的一个或多个字段在字符串中丢失怎么办。。。部分/全部是强制性的吗
  • 您可以使用反序列化器(如Gson/Jackson)将字符串反序列化为用户对象
    ObjectMapper objectMapper = new ObjectMapper();
    ...
    targetBr.lines()
            .map(line -> {
                try {
                    return objectMapper.readValue(line, User.class);
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }).collect(Collectors.toList());