admin管理员组

文章数量:1302274

With given map,

Map.of(
        "A", 5,
        "C", 13,
        "E", 2,
        "M", 5,
        "T", 45,
        "W", 2
);

How can I inflate the stream of the map's entrySet so that the stream contains,

"A", 1,
"A", 2,
"A", 3,
"A", 4,
"A", 5,

"C", 1,
"C", 2,

....

"W", 1,
"W", 2

With given map,

Map.of(
        "A", 5,
        "C", 13,
        "E", 2,
        "M", 5,
        "T", 45,
        "W", 2
);

How can I inflate the stream of the map's entrySet so that the stream contains,

"A", 1,
"A", 2,
"A", 3,
"A", 4,
"A", 5,

"C", 1,
"C", 2,

....

"W", 1,
"W", 2
Share Improve this question edited Feb 11 at 11:18 Mark Rotteveel 109k229 gold badges156 silver badges220 bronze badges asked Feb 11 at 9:03 Jin KwonJin Kwon 22k18 gold badges127 silver badges208 bronze badges 5
  • 4 Please give more details about what you're actually trying to do. If you're happy to create an iterable sequence of key/value pairs, that should be easy enough - but without more detail, this question is unanswerable. – Jon Skeet Commented Feb 11 at 9:08
  • 2 btw, be aware that Map#of does not create an instance of SequencedMap → the Map will not be created with any specified order – user85421 Commented Feb 11 at 9:11
  • actually, what is the result meant to be? A Map, with which objects? A stream with mixed content (String and Integer)? – user85421 Commented Feb 11 at 10:03
  • @user85421 (A, 5) -> (A, 1), (A, 2), (A, 3), (A, 4), (A, 5); (X, M) -> (X, 1), ..., (X, M) – Jin Kwon Commented Feb 11 at 10:28
  • 1 What is (A, 1), (A,2), ...? Output, that is just a String? A List? A Map?? (a Map would be a bit strange) -- What exactly is (A, 1) ? A String? A Map.Entry? – user85421 Commented Feb 11 at 11:31
Add a comment  | 

1 Answer 1

Reset to default 0

I solved.

Map.of("A", 5, "C", 13, "E", 2, "M", 5, "T", 45,"W", 2)
        .entrySet()
        .stream()
        .flatMap(e -> IntStream.rangeClosed(1, e.getValue())
                .mapToObj(v -> new AbstractMap.SimpleEntry<>(e.getKey(), v)))
        .forEach(e -> {
        });

Map.of("A", 5, "C", 13, "E", 2, "M", 5, "T", 45,"W", 2)
        .entrySet()
        .stream()
        .flatMap(e -> IntStream.rangeClosed(1, e.getValue())
                .mapToObj(v -> Map.entry(e.getKey(), v)))
        .forEach(e -> {
        });

Map.of("A", 5, "C", 13, "E", 2, "M", 5, "T", 45,"W", 2)
        .entrySet()
        .stream()
        .<Map.Entry<String, Integer>>mapMulti((e, c) -> IntStream.rangeClosed(1, e.getValue())
                .forEach(i -> c.accept(Map.entry(e.getKey(), i))))
        .forEach(e -> {
        });

本文标签: javaHow can I inflate entry streamStack Overflow