How to iterate inner class item using stream

Advertisements

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;
}

>Solution :

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

Leave a ReplyCancel reply