What is the best way to validate a List of JsonNodes against a Map of values?

Mark :

I have a Map that holds a name and an ID for an object. From my service, I am getting a List where each JsonNode contains a name, and should contain an id. I want to use the Map (which is authoritative) to validate the id that corresponds to the name in the JsonNode. For example:

JsonNode  Map
Mark 23   Mark 23
Chris 43  Chris 43
Ralph 21  Ralph 31

In this case, the first two match, the last doesn't. I want to iterate through all the JsonNodes and the Map and collect all the the names where the node id doesn't match the Map id.

I can make it work with the following code:

// stream all the nodes, filter the nodes with either no "id" or with an id <> expected, 
// collect into a list.
nodes.stream().filter(r -> {
            String name = r.get("name").asText();
            if (r.has("id")) {
                Long nodeId = r.get("id").asText();
                Long expectedId = map.get(name);
                if (expectedId == null) {
                    return false;
                }
                if (nodeId != map.get(name)) {
                    return true;
                } else {
                    return false;
                }
            } else { //no id in node
                return true;
            }
        }).map(r-> r.get("$id").asText()).collect(Collectors.toList());

There will be no more than 2000 JsonNodes in the list, usually much less (< 100). Does it make sense to parallelize this? If so, would using parallelStream be a good way to go? If I use parallelStream, I will create my own ForkJoinPool to better control the pool size. If not parallelStream, then would futures (like CompletableFutures) be a better way to go?

Thanks

Deadpool :

Processing list of size 2000 should not take much time, either you can use single stream like this

nodes.stream()
     .filter(r->r.has("id") && 
               !r.get("id").asText().equals(map.get(r.get("name").asText())))
     .map(r-> r.get("id").asText()).collect(Collectors.toList());

Or parallelStream, but parallel stream can consume all available processors during the execution

nodes.parallelStream()
     .filter(r->r.has("id") && 
               !r.get("id").asText().equals(map.get(r.get("name").asText())))
     .map(r-> r.get("id").asText()).collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=359080&siteId=1