我有一个包含其他对象列表的对象,该列表包含另一个对象列表。很像 DTO。 在这些对象中,有另一种类型的对象的列表,如果对象包含特定的字符串,我想删除其中的元素。
例如
CustomerDTO customerDTO = CustomerTransformer.transformCustomer(custom);
List<InfoDTO> info = customerDTO.getInfo();
info(infoDTO -> {
List<MoreDTO> d = infoDTO.getMore();
for (MoreDTO moreDTO : d) {
List<ChannelDTO> channels = MoreDTO.getChannels();
for (ChannelDTO cdto : contentChannels) {
if ("apple".equals(cdto.getId())) {
moreDTO.getChannels().remove(cdto);
}
}
}
});
但这看起来确实效率不高,并且可能会更改空指针?有没有更好的写法?使用流和在流中使用过滤器会有帮助吗?
我是 Java 新手。
最佳答案
您不能在迭代/循环时从列表中删除元素,将会出现 ConcurrentModificationException
因此,为了避免这种情况,您可以在此处使用 Java 8 Filter,以这种方式 -
contentChannels = contentChannels
.stream()
.filter(cdto->(!"apple".equals(cdto.getId())))
.collect(Collectors.toList());
另一种选择是使用 removeIf()
关于java - 如何在遍历数组时删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55936647/