[英]Filter a list of POJO using streams - getting ClassCastException java.util.LinkedHashMap cannot be cast
As familiar as the question is, my problem is a little odd. 尽管问题很熟悉,但我的问题有点奇怪。
This is the POJO I have: 这是我拥有的POJO:
public class POJO implements Serializable {
@JsonProperty("ID")
private UUID id;
@JsonProperty("Name")
private String name;
// getters and setters
}
I am trying to filter a list of this POJO using the following piece of code: 我正在尝试使用以下代码过滤此POJO的列表:
List<POJO> pojoList = getListOfPojosFromSomeMethod();
List<POJO> filteredPOJO = pojoList.stream()
.filter(p -> p.getName().equals("POJOName"))
.collect(Collectors.toList())
I am unable to filter the list. 我无法过滤列表。 I get the following exception:
我得到以下异常:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.models.POJO
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining (ArrayList.java:1374)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at
java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at
java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
I tried to use map as well: 我也尝试使用地图:
List<POJO> pojoList = getListOfPojosFromSomeMethod();
List<POJO> filteredPOJO = pojoList.stream()
.filter(p -> p.getName().equals("POJOName")
.map(p -> new POJO(p))
.collect(Collectors.toList());
Same exception. 同样的例外。 No change whatsoever.
没有任何改变。 I read somewhere that the exception is because of Jackson serialization.
我在某处读到例外是由于Jackson序列化。
How do I filter lists using streams and Jackson at the same time? 如何同时使用流和Jackson过滤列表? I am unable to find a solution.
我找不到解决方案。
Thanks in advance. 提前致谢。
You can try : 你可以试试 :
Predicate<POJO> filterPredicate = item -> "POJOName".equals(item.getName());
List<POJO> filteredPOJOs = pojoList.stream()
.filter(filterPredicate)
.collect(Collectors.toList())
There is no problem in the first example : 在第一个示例中没有问题:
List<POJO> filteredPOJO = pojoList.stream()
.filter(p -> p.getName().equals("POJOName"))
.collect(Collectors.toList());
I just noticed that a parenthesis is missing after : equals("POJOName") to close filter params. 我只是注意到在:equals(“ POJOName”)之后缺少括号以关闭过滤器参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.