gpt4 book ai didi

java - 如何删除列表中存在的空 bean 属性?

转载 作者:行者123 更新时间:2023-11-30 06:26:15 25 4
gpt4 key购买 nike

我正在使用 Spring-WS 来填充 List<SomeBean> w.r.t.网络服务。使用该服务后我得到的最终列表包含 null其某些属性的条目。例如,考虑以下 MangaBean 的列表它具有标题、作者和流派作为属性。

MangaBean [title=Bleach, author=Kubo Tite, genre=fantasy]
MangaBean [title=Naruto, author=Masashi Kishimoto, genre=action]
MangaBean [title=One Piece, author=Eiichiro Oda, genre=null]
MangaBean [title=Fairy Tail, author=Mashima Hiro, genre=null]
MangaBean [title=Rurouni Kenshin, author=Watsuki Nobuhiro, genre=Shounen]
MangaBean [title=Takamagahara, author=KAWAI Juuzou, genre=Supernatural]
MangaBean [title=Historys Strongest Disciple Kenichi, author=Matsuena Syun, genre=Martial arts]
MangaBean [title=Hajime no Ippo, author=Jyoji Morikawa, genre=null]

genre一些 bean 的条目是 null .我正在尝试删除列表中具有 null 属性 的对象。我的问题是:

  1. 通过删除特定条目来更改原始列表是否正确/良好做法?或者我应该填充另一个列表 w.r.t.上一个列表?
  2. 如果我应该更改列表并删除那些空条目,我应该怎么做?

我试过了 this但它失败了,因为对象引用本身不为空。我尝试了传统的 for 循环,但它无法删除具有空属性的附属对象。访问列表时不能使用增强型循环删除项目。请给我一些大脑。 :)

最佳答案

您可以使用迭代器并手动删除具有空类型的迭代器:

for (Iterator<MangaBean> it = mangas.iterator(); it.hasNext();) {
if (it.next().getGenre() == null) {
it.remove();
}
}

或者您可以使用一些常见的库(如 Apache Commons CollectionUtils)来过滤列表, 或 Guava Iterables.filter() :

// apache commons
mangas = CollectionUtils.filter(mangas, new Predicate() {
@Override public boolean evaluate(Object object) {
return ((Manga) manga).getGenre() != null;
}
});

// Guava
Iterables.filter(mangas, new Predicate<Manga>() {
@Override public boolean apply(Manga m) {
return manga.getGenre() != null;
}
});

关于java - 如何删除列表中存在的空 bean 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14618711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com