If you're open to using a third-party library the following will work using Eclipse Collections:
@Test
public void mapOfMapsToListOfLists()
{
MutableMap<Long, MutableSortedMap<String, String>> map = Maps.mutable.with(
1L, SortedMaps.mutable.with("key1", "value1", "key2", "value2"),
2L, SortedMaps.mutable.with("key3", "value3", "key4", "value4"));
MutableList<MutableList<String>> listOfLists = map.valuesView()
.collect(innerMap -> innerMap.keyValuesView()
.flatCollect(this::pairToList).toList())
.toList();
List<List<String>> expected = Lists.mutable.with(
Lists.mutable.with("key1", "value1", "key2", "value2"),
Lists.mutable.with("key3", "value3", "key4", "value4"));
Assert.assertEquals(expected, listOfLists);
}
public ImmutableList<String> pairToList(Pair<String, String> pair)
{
return Lists.immutable.with(pair.getOne(), pair.getTwo());
}
I initialized the inner maps as SortedMap
s in order to guarantee the order of the keys in the call to Assert.assertEquals
in the test. The interface types I used above are from Eclipse Collections and extend the JDK interface types (e.g. MutableMap extends Map, MutableList extends List), but you can also use JDK types with static utility as follows:
@Test
public void jdkMapOfMapsToListOfLists()
{
Map<Long, Map<String, String>> map = Maps.mutable.with(
1L, SortedMaps.mutable.with("key1", "value1", "key2", "value2"),
2L, SortedMaps.mutable.with("key3", "value3", "key4", "value4"));
List<List<String>> listOfLists = MapIterate.collect(map,
innerMap -> Iterate.flatCollect(
innerMap.entrySet(),
this::entryToList,
new ArrayList<>()));
List<List<String>> expected = Arrays.asList(
Arrays.asList("key1", "value1", "key2", "value2"),
Arrays.asList("key3", "value3", "key4", "value4"));
Assert.assertEquals(expected, listOfLists);
}
public List<String> entryToList(Map.Entry<String, String> entry)
{
return Arrays.asList(entry.getKey(), entry.getValue());
}
Note: I am a committer for Eclipse Collections