如何使用流迭代内部类项目

huangapple go评论54阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年7月6日 22:06:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76629690.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定