0

I have a method that receives List<String> keys and does some computations on these and at the end it returns Map<String, String> that has keys from that List and values computed or not. If value cannot be computed I want to have empty String for that key.

The clearest way would be to create Map containing all the keys with default values (empty String in that case) at the start of computations and then replace computed values.

What would be the best way to do so? There is no proper initializer in Collections API I think.

doublemc
  • 3,021
  • 5
  • 34
  • 61

3 Answers3

0
Map<String,String> map = new HashMap<>();
String emptyString = "";
for(String key:keys){
    Object yourcomputation = emptyString;
    //asign your computation to new value base on key
    map.put(key,yourcomputation);
}
Huy Nguyen
  • 1,931
  • 1
  • 11
  • 11
  • You don't want to create `new String("")`, you'll pollute the memory with duplicated empty String objects. You might want to read more about it, for example [here](https://stackoverflow.com/questions/2009228/strings-are-objects-in-java-so-why-dont-we-use-new-to-create-them). – DevDio Oct 10 '18 at 14:04
0

The easiest answer came to me seconds ago:

final Map<String, String> labelsToReturn = keys.stream().collect(toMap(x -> x, x -> ""));

solves the problem perfectly.

Just use stream and toMap with key / value mapping to initialize the map.

doublemc
  • 3,021
  • 5
  • 34
  • 61
0

I advise you to use Stream API Collectors.toMap() method. There is a way:

private static void build(List<String> keys) {
    Map<String, String> defaultValues = keys.stream().collect(
            Collectors.toMap(key -> key, key -> "default value")
    );

    // further computations
}