1
[
 {"productStatus":
    [
     {"status": "spoilt"},
     {"status": "used"}
    ],
 "productMsg":
    [
    {"msg": "Valid"}
    ]
 },
 {"productStatus":
    [
     {"status": "new"},
    ],
 "productMsg":
    [
    {"msg": "Ok"},
    {"customMsg" : "blah blah"}
    ]
 }
]

I have the above data stored in a List<Map<String, List<Map<String, String>>>>;

For example:

val is represented by Lombok library.
val firstObj = ImmutableList.of(ImmutableMap.of("status", "spoilt"),
                ImmutableMap.of("status", "new"),
                ImmutableMap.of("status", "used"));
val secondObj = ImmutableList.of(ImmutableMap.of("msg", "Valid"));
val productStatus1 = ImmutableMap.of("productStatus", firstObj,
                "productMsg", secondObj);

val firstObj_1 = ImmutableList.of(ImmutableMap.of("status", "new"));
val secondObj_2 = ImmutableList.of(ImmutableMap.of("msg", "Ok"));
val productStatus_2 = ImmutableMap.of("productStatus", firstObj_1,
                "productMsg", secondObj_2);

val testObj = ImmutableList.of(productStatus1, productStatus_2);

I need to find out if a productStatus is new, then get all the productMsgs. For example in the example I gave: I will be requiring the map of

{"msg": "Ok"},
{"customMsg" : "blah blah"}

For every productStatus which has a status new, keep adding it to a list. Basically I will need to return a List<Map<String, String>>.

I know how I can go about doing this in a traditional Java for loop method, which I feel is just too clumsy and long. Is there a neat way to do this using Streams?

shmosel
  • 49,289
  • 6
  • 73
  • 138
user1692342
  • 5,007
  • 11
  • 69
  • 128

1 Answers1

2

Untested, but I think this will do what you want:

List<Map<String, String>> msgs = testObj.stream()
        .filter(obj -> obj.get("productStatus").stream()
                .anyMatch(s -> s.get("status").equals("new")))
        .flatMap(obj -> obj.get("productMsg").stream())
        .collect(Collectors.toList());
shmosel
  • 49,289
  • 6
  • 73
  • 138