Given input (Map key:value)
"a":["e","c","d"]
"b":["c"]
Desired sorted output:
"a,c"
"a,d"
"a,e"
"b,c"
What you could possibly be looking for is using flatMap with a sort of values tweaked to compare converted integer values as :
return map.entrySet().stream()
.flatMap(e -> e.getValue().stream()
.sorted(Comparator.comparingInt(Integer::parseInt)) // or just .sorted()
.map(v -> e.getKey() + "," + v))
.collect(Collectors.toList());
To keep this readable, it's best to split the code in two methods, just so you don't inline the flatMap logic:
public List<String> toPairs(Map<String, Set<String> map) {
return map.entrySet().stream()
.flatMap(this::entryPairs)
.sorted() // if you want the whole output to be sorted
.collect(Collectors.toList())
}
private Stream<String> entryPairs(Map.Entry<String, Set<String>> entry) {
return entry.getValue().stream()
// .sorted() // you can sort the values for each key here, but this is useless if you're sorting above
.map(v -> entry.getKey() + ',' + v)
}
map.forEach((k,v) -> v.forEach( val -> list.add(k + "," +val))). Give it a try once!