如何使用流API将类型对象的实例映射到Java中的特定类
我遇到了以下问题:
如果我将流中的对象映射到Java中的特定类,则Java流API在映射后无法识别特定对象,并且仍然假定它是对象。我在做什么错,是否有一种方法可以解决这个问题,而没有潜在的班级铸造例外?
这是代码示例:
public class MyMapper {
MyMapper() {
Object someObject = new Person();
final var listOfObjects = List.of(someObject);
final var listOfPerson = toListOfPerson(listOfObjects);
}
List<Optional<Person>> toListOfPerson(Object object) {
return ((List) object).stream()
.map(this::toPerson)
.collect(Collectors.toList());
}
Optional<Person> toPerson(Object object) {
if (object instanceof Person) {
return Optional.of((Person) object);
}
return Optional.empty();
}
public class Person {}
}
I've encountered the following problem:
If I map an object in a stream to a specific class in Java, the java stream API does not recognize a specific object after the mapping and still assumes it is an object. What am I doing wrong, and is there a way to solve this without potential class cast exceptions?
Here is the code example:
public class MyMapper {
MyMapper() {
Object someObject = new Person();
final var listOfObjects = List.of(someObject);
final var listOfPerson = toListOfPerson(listOfObjects);
}
List<Optional<Person>> toListOfPerson(Object object) {
return ((List) object).stream()
.map(this::toPerson)
.collect(Collectors.toList());
}
Optional<Person> toPerson(Object object) {
if (object instanceof Person) {
return Optional.of((Person) object);
}
return Optional.empty();
}
public class Person {}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将其投入到键入列表中,然后将您的 .map(this :: toperson)将其“接受”此列表的元素
cast it to a typed List and then your .map(this::toPerson) will "accept" the element of this List
保持可选对象的集合可能是空的,这是没有意义的,它可能是空的,几乎与存储
null
值相同。如果您出于某种原因认为
list&lt; lt; person&gt;&gt;
是个好主意,我建议您查看这个问题。 Stuart Marks(JDK开发人员)的答案引用:在JDK中引入了可选的作为有限的机制,以代表A Nullable返回值。这是它的唯一目的,其他使用可选对象(例如可选方法参数,字段,选项集合)的情况被认为是反对的。
您必须在流中解开
可选
s:It doesn't make sense to keep the collection of optional objects which could be potentially empty, it almost the same as storing
null
values.If you think for some reason that
List<Optional<Person>>
is good idea, I recommend you to have a look at this question. A quote from the answer by Stuart Marks (JDK developer):Optional was introduced in the JDK as a limited mechanism to represent a nullable return value. That is its only purpose, other cases of usage of optional objects like optional method arguments, fields, collections of optionals are considered to be antipattern.
You have to unpack your
Optional
s in the stream: