Skip to content
Advertisement

how do I convert this piece of code to stream using java stream api

I am trying to convert below code into stream. It’s not that difficult but I am not sure how to handle null values in stream. I did checked out Optinal.ofNullable method but quite not sure if I have to use it 2-3 times to get the correct stream code. I can use the below code for now, but I wish to learn doing it in stream. Please help me learn.

Map<String, Map<String, List<String>>> fileTypeMapping = new HashMap<>();

Map<String, List<String>> map = new HashMap<>();
    map.put("codec", new ArrayList(Arrays.asList("ext1", "ext2")));
    fileTypeMapping.put("image", map);

String fileType = "Image";
String codec = "Codec";
String extension = "ext2";
boolean exist = false;
if(fileType != null) {
    Map<String, List<String>> codecMap = fileTypeMapping.get(fileType.toLowerCase());
    if(codecMap != null) {
        List<String> list = codecMap.get(codec.toLowerCase());
        if (list != null) {
            exist = list.contains(extension.toLowerCase());
        }
    }
}
System.out.print(exist);

Advertisement

Answer

Seems not related to Stream API, just use Map.getOrDefault to get rid of null return.

import java.util.*;

public class NullableMapGet {
    public static void main(String[] args) {
        Map<String, Map<String, List<String>>> fileTypeMapping = new HashMap<>();

        Map<String, List<String>> map = new HashMap<>();
        map.put("codec", new ArrayList(Arrays.asList("ext1", "ext2")));
        fileTypeMapping.put("image", map);

        String fileType = "Image";
        String codec = "Codec";
        String extension = "ext2";
        boolean exist = false;
        if (fileType == null || codec == null || extension == null) {
            exist = false;
        } else {
            exist = fileTypeMapping
                    .getOrDefault(fileType.toLowerCase(), Collections.emptyMap())
                    .getOrDefault(codec.toLowerCase(), Collections.emptyList())
                    .contains(extension.toLowerCase());
        }
        System.out.print(exist);
    }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement