1

Given input (Map key:value)

"a":["e","c","d"]
"b":["c"]

Desired sorted output:

"a,c"
"a,d"
"a,e"
"b,c"
9
  • Google "how to use flatMap with java stream" Commented Mar 14, 2019 at 17:29
  • It could really be as simple as : map.forEach((k,v) -> v.forEach( val -> list.add(k + "," +val))) . Give it a try once! Commented Mar 14, 2019 at 17:32
  • @Naman that's a bad solution, it's not very functional Commented Mar 14, 2019 at 17:34
  • @hey_you alright, what is not functional in it? could you elaborate bad here in terms of what? Commented Mar 14, 2019 at 17:34
  • @Naman the fact that you're using foreach everywhere, might as well write a normal for instead. Commented Mar 14, 2019 at 17:35

3 Answers 3

1

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());
Sign up to request clarification or add additional context in comments.

Comments

1

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)
}

Comments

0

Not sure if it is a perfect solution but it is working.

map.entrySet().stream()
  .map(entry.getValue().stream()
     .sorted()
     .map(value->entry.getKey()+","+value)
     .collect(Collectors.joining("\n"))
  )
  .sorted()
  .collect(Collectors.joining("\n"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.