英文:
How to iterate inner class item using stream
问题
我尝试打印所有的sourceKey,我尝试了类似以下的方法(虽然是不完整的):
System.out.println(person.prsndtl.items.stream().map(PrsnDtl.Item::toString));
sourceKey的值类似于以下内容:
AAA:C:22
BBB:C:44
我想要通过迭代所有的项来打印出只有22和44。如何迭代并打印它们,提前感谢。
英文:
I have below classes hierarchy. I am trying to print all the sourceKey.
I was trying something like below (incomplete though)
System.out.println(person.prsndtl.items.stream().map(PrsnDtl.Item::toString));
sourceKey values are something like below.
AAA:C:22
BBB:C:44
I want to print only 22, 44 by iterating all items.
How do I iterate and print them, thanks in advance
@Getter
@Setter
@ToString
public class Person {
@JsonProperty("MyPrsnDtl")
public PrsnDtl prsndtl;
}
@Getter
@Setter
@ToString
public class PrsnDtl {
@JsonProperty("item")
@Getter
@Setter
public List<Item> items = new ArrayList<>();
@Getter
@Setter
@ToString
public static final class Item {
@JsonProperty("key")
public Key key;
}
}
@Getter
@Setter
@ToString
public class Key {
@JsonProperty("sourceKey")
public String sourceKey;
}
答案1
得分: 1
根据我看到的,你可以使用字符串拆分来拆分字符串并获取sourceKey内容的最后一个“列”:
var allIds = person.getPrsndtl()
.getItems()
.stream()
.map(item -> item.getKey())
.map(key -> key.getSourceKey())
.map(sourceKey -> sourceKey.split(":")[2])
.toList();
但这只在格式始终相同的情况下有效。如果不是的话,你需要编写保障措施。
英文:
As far as i see you can use string split to split the string and get the last "column" of the sourceKey contents:
var allIds = person.getPrsndtl()
.getItems()
.stream()
.map(item -> item.getKey())
.map(key -> key.getSourceKey())
.map(sourceKey -> sourceKey.split(":")[2])
.toList();
But this only works if the format is really always the same. If not, then you need to write in safeguards
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论