I have an ArrayListMultimap like
ArrayListMultimap<Long, String> multiMap = ArrayListMultimap.create();
multiMap.put(100L,"test1");
multiMap.put(750L,"test0");
multiMap.put(50L, "test2");
multiMap.put(500L, "test3");
multiMap.put(200L, "test45");
multiMap.put(200L, "test000");
multiMap.put(60L, "test48");
which gives me {50=[test2], 100=[test1], 500=[test3], 200=[test45, test000], 60=[test48], 750=[test0]}
.
I want to add all the keys to a list but the keys with multiple values need to be added based on the size of the value list. For example, in the above example, I want 200
to be added twice to the list since the size of its value is 2. I have tried using ArrayList<Long> keyList = pathSizeMap.keySet()
but this gives me just the keys.
How can I achieve this preferably using Java 8 streams?
Note that keySet()
specifically says Set (as in the collection that has no duplicate entries). That's why you're getting a single copy of each key.
Instead of using keySet()
just stream the entries and get the key of each one:
List<Long> list = multiMap.entries().stream().map(Entry::getKey).collect(Collectors.toList());
System.out.println(list)
Output:
[100, 200, 200, 750, 50, 500, 60]