values
in the code below comes from redis. What’s the best way to convert it back to a list of Items
. I am new to Java and have this code below but I am hoping there’s a better way?
@AllArgsConstructor
public class Item {
public String key;
public Map<String, Integer> values;
}
public static List<Item> getItems() {
Map<String, String> values = Map.of("k1", "{"key1":1,"key2":2}", "k2", "{"key1":3,"key2":4}");
List<Item> items = values.entrySet().stream().map(entry -> {
try {
TypeReference<HashMap<String, Integer>> typeRef = new TypeReference<HashMap<String, Integer>>() {};
var itemValues = new ObjectMapper().readValue(entry.getValue(), typeRef);
return Optional.of(new Item(entry.getKey(), itemValues));
} catch (JsonProcessingException ex) {
Optional<Item> emptyItem = Optional.empty();
return emptyItem;
}
}).flatMap(Optional::stream).collect(Collectors.toList());
return items;
}
2
Answers
Immutable values should be declared as constants. The part that throws an exception in the lambda expression should be a separate method.
Instead of using Optional to manage the default case, you can use Stream’s flatMap.
MAPPER.readerForMapOf
is a shortcut ofnew TypeReference<..>