0

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

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

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.