[英]Using Java 8 to convert a list of String into a list of Object
There is a stream read from file, the content of each line is like: 有一个从文件读取的流,每一行的内容如下:
{"uid":"5981865218","timestamp":1525309552069,"isHot":true}
The class of User: 用户类别:
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;
}
}
The code that I want to get a list of Object 'List' from file stream: 我想从文件流中获取对象“列表”列表的代码:
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());
You need to deserialize the String to User
objects. 您需要将String反序列化为
User
对象。 I have used Jackson ObjectMapper here (you could very well use others like Gson). 我在这里使用过Jackson Jackson ObjectMapper (您可以很好地使用Gson等其他产品)。
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());
The map
part of the stream takes a Function
and hence you cannot throw a checked exception from there. 流的
map
部分带有一个Function
,因此您不能从那里抛出一个检查异常。 Hence, I have wrapped the IOException
that Jackson readValue
throws (could throw) into a RuntimeException. 因此,我将Jackson的
readValue
抛出(可能抛出)的IOException
封装到RuntimeException中。 You might have to change that part according to your need. 您可能需要根据需要更改该部分。
This is just a start. 这只是一个开始。 Think about what to do when there is an invalid entry that cannot be deserialized into a
User
. 考虑当存在无法反序列化为
User
的无效条目时该怎么办。 Some specific corner cases: 一些特定的极端情况:
UnrecognizedPropertyException
exception. UnrecognizedPropertyException
异常。 You can find ways to ignore it.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.