Home > Enterprise >  Loop through a list of map effectively
Loop through a list of map effectively

Time:12-22

Basically I have a List<Map<String, Object>> listOfValueand I need to check if the object is instance of byte then encode it to String as shown below:

private void convertByteToBase64(List<Map<String, Object>> listOfValue) {

Object value = null;


if (!CollectionUtils.isEmpty(listOfValue)) {

    for (Map<String, Object> map : listOfValue) {

        if (!map.isEmpty()) {

            for (Map.Entry<String, Object> entry : map.entrySet()) {

                value = entry.getValue();

                if (value instanceof byte[]) {

                    entry.setValue(Base64.getEncoder().encodeToString((byte[]) value));
                }
            }

        }

    }

}

}

I am using java 8 and it is working as expected but is it the correct way of doing it or any better way in term of performance?

CodePudding user response:

Current implementation seems to be ok, however, checking for emptiness of the list and the nested maps seems to be redundant.

Some performance improvement may be possibly achieved if parallel streams are used to iterate the list/maps.

private void convertByteToBase64(List<Map<String, Object>> listOfValue) {
    Base64.Encoder base64encoder = Base64.getEncoder();
    listOfValue.parallelStream()
        .flatMap(map -> map.entrySet().parallelStream())
        .filter(entry -> entry.getValue() instanceof byte[])
        .forEach(entry -> entry.setValue(
            base64encoder.encodeToString((byte[]) entry.getValue())
        ));
}

Base64.Encoder is thread-safe: Instances of Base64.Encoder class are safe for use by multiple concurrent threads..

CodePudding user response:

Alternatively, you can use parallelStream and filter as below.

private void convertByteToBase64(List<Map<String, Object>> listOfValue) {
           listOfValue.parallelStream().forEach(map -> {
            map.entrySet().parallelStream().filter(entry->entry.getValue() instanceof byte[]).forEach(entry -> {
                entry.setValue(Base64.getEncoder().encodeToString((byte[]) entry.getValue()));
            });
          });`
}

CodePudding user response:

public static void convertByteToBase64(List<Map<String, Object>> listOfValue) {

    listOfValue.stream().parallel()
            .forEach(map -> map.forEach((key,value)->{
                if(value instanceof byte[]) {
                    map.put(key, Base64.getEncoder().encodeToString((byte[])value))  ;
        }
    }));
}
  •  Tags:  
  • java
  • Related