user1999453
user1999453

Reputation: 1433

Loop through a list of map effectively

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?

Upvotes: 0

Views: 67

Answers (3)

Nowhere Man
Nowhere Man

Reputation: 19565

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..

Upvotes: 2

Oussama ZAGHDOUD
Oussama ZAGHDOUD

Reputation: 2169

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

Upvotes: 0

Semih Ozturk
Semih Ozturk

Reputation: 57

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()));
            });
          });`
}

Upvotes: 0

Related Questions