Roman Cherepanov
Roman Cherepanov

Reputation: 1805

Can I map one element to many using Stream?

Is it possible to map one collection to another with Java Streams, but second collection must to have different element count than first?

I have map

"1" -> 10, "2-3" -> 20

and want convert it to

List<Node> = Node(1,10), Node(2,20), Node(3,20)

How can I do this using streams?

My code is:

import com.google.common.collect.ImmutableMap;

import java.util.*;

import static java.util.stream.Collectors.toList;

public class MapOneToManyQuestion {

    public static void main(String[] args) {
        new MapOneToManyQuestion().run();
    }

    void run() {
        final Map<String, Integer> map = ImmutableMap.of("1", 10, "2-3", 20);

        List<Node> nodes = map.entrySet().stream().map(entry -> {
            if (Objects.equals(entry.getKey(), "1")) {
                return new Node(1, entry.getValue());
            } else {
                //return new Node(2, entry.getValue());
                //return new Node(3, entry.getValue());
            }
        }).collect(toList());
    }

    class Node {
        private Integer key;
        private Integer value;

        public Node(Integer key, Integer value) {
            this.key = key;
            this.value = value;
        }

        public Integer key() {
            return this.key;
        }

        public Integer value() {
            return this.value;
        }
    }
}

Upvotes: 0

Views: 116

Answers (1)

Thiyagu
Thiyagu

Reputation: 17920

You can use a flatMap for this

List<Node> nodes = map.entrySet()
        .stream()
        .flatMap(entry -> {
            String key = entry.getKey();
            Integer value = entry.getValue();
            return Arrays.stream(key.split("-"))
                    .map(splitKey -> new Node(Integer.valueOf(splitKey), value));
        })
        .collect(Collectors.toList());

It streams through each map element and it splits the key by - and creates one Node object for each key part resulting from the split and the map value for that entry and finally it gets collected to a list.

Upvotes: 3

Related Questions