BigO
BigO

Reputation: 98

Using string stream as split result in lambda

I need to split line based on comma and add it to a Map simultaneously in one go. I know that I can collect the splitted stream to list and then iterate over list for same effect. But I need to know if that can be done.

Input : List<String> - (A, B) (A,C)

Output : Map<String, List<String>> - (A, (B,C))

Example Code : (Contains Error)

public void edgeListRepresentation(ArrayList<String> edges){
        Map<String, List<String>> edgeList = new HashMap<>();
        edges.forEach(connection -> {

            Stream.of(connection.split(","))
                    .map((arr) -> {
                        edgeList.computeIfAbsent(arr[0], val -> new ArrayList<String>()).add(arr[1]);
                    });
        });

    }

     public static void main(String[] args) throws IOException {
        EdgeList edgeList = new EdgeList();
        edgeList.edgeListRepresentation(new ArrayList<String>(){
            {
                add("A, B");
                add("A, C");
                add("A, E");
                add("B, C");
                add("C, E");
                add("C, D");
                add("D, E");
            }
        });
    }

Upvotes: 0

Views: 376

Answers (2)

Eklavya
Eklavya

Reputation: 18430

If you want to make it simple in your way, no need to use stream

edges.forEach(connection -> {
  String[] arr = connection.split(",");
  edgeList.computeIfAbsent(arr[0], val -> new ArrayList<String>()).add(arr[1].trim());
});

Upvotes: 1

slesh
slesh

Reputation: 2007

You may solve your problem by using map + groupBy + mapping. Split all your lines by comma and put the result into common List of tuples. In the end, just apply groupBy collector and mapping to pick up only value from tuple. For example:

new ArrayList<String>() {
    {
        add("A, B");
        add("A, C");
        add("A, E");
        add("B, C");
        add("C, E");
        add("C, D");
        add("D, E");
    }
}.stream()
    .map(line -> line.split(","))
    .collect(Collectors.groupingBy(
        tuple -> tuple[0],
        Collectors.mapping(
            tuple -> tuple[1].trim(),
            Collectors.toList())
    ))

Output: {A=[B, C, E], B=[C], C=[E, D], D=[E]}

Upvotes: 2

Related Questions