rakesh_parashar
rakesh_parashar

Reputation: 829

Add HashMap into list then add generated list to new HashMap using a lambda expression

I have the below code, which works fine. In this code, its adding an element in LinkedHashMap, this Map is then added to a new list, and finally, that list is added into another LinkedHashMap. I am trying to find a better short way using java8 to make it more simple and short, any suggestion?

private Object getData() {
        LinkedHashMap<String, String> secondLevelMap = new LinkedHashMap<>();
        secondLevelMap.put("href", "http://SomeLink");
        List<LinkedHashMap> firstLevelList = new ArrayList<>(2);
        firstLevelList.add(null);
        firstLevelList.add(secondLevelMap);
        LinkedHashMap<String, List<LinkedHashMap>> firstLevelMap = new LinkedHashMap<>();
        firstLevelMap.put("links", firstLevelList);
        return firstLevelMap;
    }

Upvotes: 0

Views: 138

Answers (1)

Nowhere Man
Nowhere Man

Reputation: 19545

Here a couple of helper methods could be implemented to create a map using a Supplier<Map>, populate it with a default key-value and return the map.

As for list, there is method Arrays.asList to create a list from object(s), which may be used as is if a fixed-size list is fine, or can be wrapped into new ArrayList<>(Arrays.asList(...)) to create a fully mutable list.

private static <K, V> Map<K, V> createMap(K key, V value) {
    return createMap(key, value, LinkedHashMap::new);
}

private static <K, V> Map<K, V> createMap(K key, V value, Supplier<Map<K, V>> mapSupplier) {
    Map<K, V> map = mapSupplier.get();
    map.put(key, value);

    return map;
}

Then getData may be rewritten as follows (also, fixed the raw Object in return type):

public Map<String, List<Map<String, String>>> getData() {
    return createMap("links", new ArrayList<>(
            Arrays.asList(null, createMap("href", "http://SomeLink"))
    ));
}

Test

System.out.println(new MyClass().getData());

Output:

{links=[null, {href=http://SomeLink}]}

For exercise purpose, a couple of "lambdas" may be defined to refer createMap method with specific type of arguments:

BiFunction<String, String, Map<String, String>> innerMapSupplier = (k, v) -> MyClass.createMap(k, v);
BiFunction<String, List<Map<String, String>>, Map<String, List<Map<String, String>>>> resultMapSupplier = (k, v) -> MyClass.createMap(k, v);

System.out.println(
    resultMapSupplier.apply("links", Arrays.asList(
        null, 
        innerMapSupplier.apply("href", "http://SomeLink")
    ))
);

Upvotes: 1

Related Questions