Get latest jsons with respect to [version and name] key in subjson in java
First of all, you have a grouping operation by process name, then you have the task of finding the maximum by version number per group.

Thus, instead of using nested loops and somehow mashing it all together, simply perform those operations.

As standard operations like grouping and finding a maximum are alreay presenet in the java stream api, all we need is a few helpers to extract the name and the version:

Function&lt;Map&lt;String, Object&gt;, String&gt; extractName = m -&gt; (String) ((Map&lt;String, Object&gt;) m.get("SUBTASK")).get("name");
ToDoubleFunction&lt;Map&lt;String, Object&gt;&gt; extractVersion = m -&gt; Double.parseDouble((String) ((Map&lt;String, Object&gt;) m.get("SUBTASK")).get("version"));


Then, first group by name:

Map&lt;String, List&lt;Map&lt;String, Object&gt;&gt;&gt; byName = taskList.stream()
    .collect(Collectors.groupingBy(extractName));


... which gives you a list of each task type in the value lists.

Now, we can disregard the grouping keys and extract the maximum per list:

List&lt;Map&lt;String, Object&gt;&gt; result = byName.values().stream()
    .map(l -&gt; l.stream().max(Comparator.comparingDouble(extractVersion)))
    .map(Optional::get)
    .collect(Collectors.toList());


Note: the stream.max returns an optional, which would be unset for an empty list. As we cannot generate empty lists here, it is save to simply map via Optional::get to retrieve the value.

All is left is to encode the result list back to json, e.g.

String jsonResult = new GsonBuilder().setPrettyPrinting().create().toJson(result);


Note however, that you should better use a method which operates directly on the data structures, i.e. input and output are List&lt;Map&lt;String, Object&gt;&gt; and another outer wrapper method to do the decoding and encoding. Do one thing in a method.