Converting a text file to Map<String, List> using lambda












7















I am trying to convert the following text input file:



A=groupA1
A=groupA2
A=groupA3
B=groupB1
B=groupB2


into Map<String, List<String>> by splitting each line on "="



So far I manged to get this sort of output:



KEY: A
VALUE: A=groupA1
VALUE: A=groupA2
VALUE: A=groupA3
KEY: B
VALUE: B=groupB1
VALUE: B=groupB2


using such code:



File reqFile = new File("test.config");

try (Stream<String> stream = Files.lines(reqFile.toPath())) {
Map<String, List<String>> conf = stream.collect(Collectors.groupingBy(s -> s.split("=")[0]));
for (Map.Entry<String, List<String>> entry: conf.entrySet()) {
System.out.println("KEY: " + entry.getKey());
for (String value : entry.getValue()) {
System.out.println("VALUE: " + value);
}
}
} catch (Exception e) {
e.printStackTrace();
}


How to tweak the above lambda to get something like this:



KEY: A
VALUE: groupA1
VALUE: groupA2
VALUE: groupA3
KEY: B
VALUE: groupB1
VALUE: groupB2









share|improve this question









New contributor




BartD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 2





    much like regular expressions, once you decide to solve a problem with lambdas now you have two problems ( if you do not 100% comprehend what you are doing and why you are doing it that way ). Regular non-lambda solution would be far more efficient and more importantly readable and maintainable.

    – Jarrod Roberson
    3 hours ago
















7















I am trying to convert the following text input file:



A=groupA1
A=groupA2
A=groupA3
B=groupB1
B=groupB2


into Map<String, List<String>> by splitting each line on "="



So far I manged to get this sort of output:



KEY: A
VALUE: A=groupA1
VALUE: A=groupA2
VALUE: A=groupA3
KEY: B
VALUE: B=groupB1
VALUE: B=groupB2


using such code:



File reqFile = new File("test.config");

try (Stream<String> stream = Files.lines(reqFile.toPath())) {
Map<String, List<String>> conf = stream.collect(Collectors.groupingBy(s -> s.split("=")[0]));
for (Map.Entry<String, List<String>> entry: conf.entrySet()) {
System.out.println("KEY: " + entry.getKey());
for (String value : entry.getValue()) {
System.out.println("VALUE: " + value);
}
}
} catch (Exception e) {
e.printStackTrace();
}


How to tweak the above lambda to get something like this:



KEY: A
VALUE: groupA1
VALUE: groupA2
VALUE: groupA3
KEY: B
VALUE: groupB1
VALUE: groupB2









share|improve this question









New contributor




BartD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 2





    much like regular expressions, once you decide to solve a problem with lambdas now you have two problems ( if you do not 100% comprehend what you are doing and why you are doing it that way ). Regular non-lambda solution would be far more efficient and more importantly readable and maintainable.

    – Jarrod Roberson
    3 hours ago














7












7








7


1






I am trying to convert the following text input file:



A=groupA1
A=groupA2
A=groupA3
B=groupB1
B=groupB2


into Map<String, List<String>> by splitting each line on "="



So far I manged to get this sort of output:



KEY: A
VALUE: A=groupA1
VALUE: A=groupA2
VALUE: A=groupA3
KEY: B
VALUE: B=groupB1
VALUE: B=groupB2


using such code:



File reqFile = new File("test.config");

try (Stream<String> stream = Files.lines(reqFile.toPath())) {
Map<String, List<String>> conf = stream.collect(Collectors.groupingBy(s -> s.split("=")[0]));
for (Map.Entry<String, List<String>> entry: conf.entrySet()) {
System.out.println("KEY: " + entry.getKey());
for (String value : entry.getValue()) {
System.out.println("VALUE: " + value);
}
}
} catch (Exception e) {
e.printStackTrace();
}


How to tweak the above lambda to get something like this:



KEY: A
VALUE: groupA1
VALUE: groupA2
VALUE: groupA3
KEY: B
VALUE: groupB1
VALUE: groupB2









share|improve this question









New contributor




BartD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












I am trying to convert the following text input file:



A=groupA1
A=groupA2
A=groupA3
B=groupB1
B=groupB2


into Map<String, List<String>> by splitting each line on "="



So far I manged to get this sort of output:



KEY: A
VALUE: A=groupA1
VALUE: A=groupA2
VALUE: A=groupA3
KEY: B
VALUE: B=groupB1
VALUE: B=groupB2


using such code:



File reqFile = new File("test.config");

try (Stream<String> stream = Files.lines(reqFile.toPath())) {
Map<String, List<String>> conf = stream.collect(Collectors.groupingBy(s -> s.split("=")[0]));
for (Map.Entry<String, List<String>> entry: conf.entrySet()) {
System.out.println("KEY: " + entry.getKey());
for (String value : entry.getValue()) {
System.out.println("VALUE: " + value);
}
}
} catch (Exception e) {
e.printStackTrace();
}


How to tweak the above lambda to get something like this:



KEY: A
VALUE: groupA1
VALUE: groupA2
VALUE: groupA3
KEY: B
VALUE: groupB1
VALUE: groupB2






java java-8 java-stream






share|improve this question









New contributor




BartD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




BartD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 3 hours ago









Deadpool

5,1822528




5,1822528






New contributor




BartD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 3 hours ago









BartDBartD

383




383




New contributor




BartD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





BartD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






BartD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 2





    much like regular expressions, once you decide to solve a problem with lambdas now you have two problems ( if you do not 100% comprehend what you are doing and why you are doing it that way ). Regular non-lambda solution would be far more efficient and more importantly readable and maintainable.

    – Jarrod Roberson
    3 hours ago














  • 2





    much like regular expressions, once you decide to solve a problem with lambdas now you have two problems ( if you do not 100% comprehend what you are doing and why you are doing it that way ). Regular non-lambda solution would be far more efficient and more importantly readable and maintainable.

    – Jarrod Roberson
    3 hours ago








2




2





much like regular expressions, once you decide to solve a problem with lambdas now you have two problems ( if you do not 100% comprehend what you are doing and why you are doing it that way ). Regular non-lambda solution would be far more efficient and more importantly readable and maintainable.

– Jarrod Roberson
3 hours ago





much like regular expressions, once you decide to solve a problem with lambdas now you have two problems ( if you do not 100% comprehend what you are doing and why you are doing it that way ). Regular non-lambda solution would be far more efficient and more importantly readable and maintainable.

– Jarrod Roberson
3 hours ago












3 Answers
3






active

oldest

votes


















3














Map and collect:



Map<String, List<String>> res = lines.stream()
.map(s -> Arrays.asList(s.split("=")))
.collect(HashMap::new,
(map, item) -> map.computeIfAbsent(item.get(0), k -> new ArrayList<>()).add(item.get(1)),
HashMap::putAll);


Or map and group by:



Map<String, List<String>> res = lines.stream()
.map(s -> Arrays.asList(s.split("=")))
.collect(Collectors.groupingBy(s -> s.get(0), Collectors.mapping(v->v.get(1), Collectors.toList())));




  1. Stream.collect documentation






share|improve this answer


























  • This one also works nicely! Thank you @Michał Ziober

    – BartD
    3 hours ago











  • No problem. Mapping solves problem with splitting items two times. I have also added a version with grouping by collectors. If you think it is helpful for you, please, upvote it.

    – Michał Ziober
    3 hours ago



















2














Use Collectors.mapping while groupingBy, for more information look at this doc-with-example



Map<String, List<String>> conf = stream.    
collect(Collectors.groupingBy(s -> s.split("=")[0], Collectors.mapping(v->v.split("=")[1], Collectors.toList())));

System.out.println(conf); //{A=[groupA1, groupA2, groupA3], B=[groupB1, groupB2]}





share|improve this answer





















  • 1





    That is exactly what I was looking for! Map<String, List<String>> conf = stream.collect(Collectors.groupingBy(s -> s.split("=")[0], Collectors.mapping(v->v.split("=")[1], Collectors.toList()))); and the output: KEY: A VALUE: groupA1 VALUE: groupA2 VALUE: groupA3 KEY: B VALUE: groupB1 VALUE: groupB2

    – BartD
    3 hours ago





















0














If you are open to using a third-party library, the following will work using Eclipse Collections.



ListMultimap<String, String> strings = stream
.map(s -> s.split("="))
.collect(Collectors2.toListMultimap(a -> a[0], a -> a[1]));


Collectors2.toListMultimap takes a Function to calculate the key and a separate Function to calculate the value. The ListMultimap<K, V> type is equivalent to Map<K, List<V>>.



Note: I am a committer for Eclipse Collections.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });






    BartD is a new contributor. Be nice, and check out our Code of Conduct.










    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54383490%2fconverting-a-text-file-to-mapstring-liststring-using-lambda%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    Map and collect:



    Map<String, List<String>> res = lines.stream()
    .map(s -> Arrays.asList(s.split("=")))
    .collect(HashMap::new,
    (map, item) -> map.computeIfAbsent(item.get(0), k -> new ArrayList<>()).add(item.get(1)),
    HashMap::putAll);


    Or map and group by:



    Map<String, List<String>> res = lines.stream()
    .map(s -> Arrays.asList(s.split("=")))
    .collect(Collectors.groupingBy(s -> s.get(0), Collectors.mapping(v->v.get(1), Collectors.toList())));




    1. Stream.collect documentation






    share|improve this answer


























    • This one also works nicely! Thank you @Michał Ziober

      – BartD
      3 hours ago











    • No problem. Mapping solves problem with splitting items two times. I have also added a version with grouping by collectors. If you think it is helpful for you, please, upvote it.

      – Michał Ziober
      3 hours ago
















    3














    Map and collect:



    Map<String, List<String>> res = lines.stream()
    .map(s -> Arrays.asList(s.split("=")))
    .collect(HashMap::new,
    (map, item) -> map.computeIfAbsent(item.get(0), k -> new ArrayList<>()).add(item.get(1)),
    HashMap::putAll);


    Or map and group by:



    Map<String, List<String>> res = lines.stream()
    .map(s -> Arrays.asList(s.split("=")))
    .collect(Collectors.groupingBy(s -> s.get(0), Collectors.mapping(v->v.get(1), Collectors.toList())));




    1. Stream.collect documentation






    share|improve this answer


























    • This one also works nicely! Thank you @Michał Ziober

      – BartD
      3 hours ago











    • No problem. Mapping solves problem with splitting items two times. I have also added a version with grouping by collectors. If you think it is helpful for you, please, upvote it.

      – Michał Ziober
      3 hours ago














    3












    3








    3







    Map and collect:



    Map<String, List<String>> res = lines.stream()
    .map(s -> Arrays.asList(s.split("=")))
    .collect(HashMap::new,
    (map, item) -> map.computeIfAbsent(item.get(0), k -> new ArrayList<>()).add(item.get(1)),
    HashMap::putAll);


    Or map and group by:



    Map<String, List<String>> res = lines.stream()
    .map(s -> Arrays.asList(s.split("=")))
    .collect(Collectors.groupingBy(s -> s.get(0), Collectors.mapping(v->v.get(1), Collectors.toList())));




    1. Stream.collect documentation






    share|improve this answer















    Map and collect:



    Map<String, List<String>> res = lines.stream()
    .map(s -> Arrays.asList(s.split("=")))
    .collect(HashMap::new,
    (map, item) -> map.computeIfAbsent(item.get(0), k -> new ArrayList<>()).add(item.get(1)),
    HashMap::putAll);


    Or map and group by:



    Map<String, List<String>> res = lines.stream()
    .map(s -> Arrays.asList(s.split("=")))
    .collect(Collectors.groupingBy(s -> s.get(0), Collectors.mapping(v->v.get(1), Collectors.toList())));




    1. Stream.collect documentation







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 3 hours ago

























    answered 3 hours ago









    Michał ZioberMichał Ziober

    12.9k967101




    12.9k967101













    • This one also works nicely! Thank you @Michał Ziober

      – BartD
      3 hours ago











    • No problem. Mapping solves problem with splitting items two times. I have also added a version with grouping by collectors. If you think it is helpful for you, please, upvote it.

      – Michał Ziober
      3 hours ago



















    • This one also works nicely! Thank you @Michał Ziober

      – BartD
      3 hours ago











    • No problem. Mapping solves problem with splitting items two times. I have also added a version with grouping by collectors. If you think it is helpful for you, please, upvote it.

      – Michał Ziober
      3 hours ago

















    This one also works nicely! Thank you @Michał Ziober

    – BartD
    3 hours ago





    This one also works nicely! Thank you @Michał Ziober

    – BartD
    3 hours ago













    No problem. Mapping solves problem with splitting items two times. I have also added a version with grouping by collectors. If you think it is helpful for you, please, upvote it.

    – Michał Ziober
    3 hours ago





    No problem. Mapping solves problem with splitting items two times. I have also added a version with grouping by collectors. If you think it is helpful for you, please, upvote it.

    – Michał Ziober
    3 hours ago













    2














    Use Collectors.mapping while groupingBy, for more information look at this doc-with-example



    Map<String, List<String>> conf = stream.    
    collect(Collectors.groupingBy(s -> s.split("=")[0], Collectors.mapping(v->v.split("=")[1], Collectors.toList())));

    System.out.println(conf); //{A=[groupA1, groupA2, groupA3], B=[groupB1, groupB2]}





    share|improve this answer





















    • 1





      That is exactly what I was looking for! Map<String, List<String>> conf = stream.collect(Collectors.groupingBy(s -> s.split("=")[0], Collectors.mapping(v->v.split("=")[1], Collectors.toList()))); and the output: KEY: A VALUE: groupA1 VALUE: groupA2 VALUE: groupA3 KEY: B VALUE: groupB1 VALUE: groupB2

      – BartD
      3 hours ago


















    2














    Use Collectors.mapping while groupingBy, for more information look at this doc-with-example



    Map<String, List<String>> conf = stream.    
    collect(Collectors.groupingBy(s -> s.split("=")[0], Collectors.mapping(v->v.split("=")[1], Collectors.toList())));

    System.out.println(conf); //{A=[groupA1, groupA2, groupA3], B=[groupB1, groupB2]}





    share|improve this answer





















    • 1





      That is exactly what I was looking for! Map<String, List<String>> conf = stream.collect(Collectors.groupingBy(s -> s.split("=")[0], Collectors.mapping(v->v.split("=")[1], Collectors.toList()))); and the output: KEY: A VALUE: groupA1 VALUE: groupA2 VALUE: groupA3 KEY: B VALUE: groupB1 VALUE: groupB2

      – BartD
      3 hours ago
















    2












    2








    2







    Use Collectors.mapping while groupingBy, for more information look at this doc-with-example



    Map<String, List<String>> conf = stream.    
    collect(Collectors.groupingBy(s -> s.split("=")[0], Collectors.mapping(v->v.split("=")[1], Collectors.toList())));

    System.out.println(conf); //{A=[groupA1, groupA2, groupA3], B=[groupB1, groupB2]}





    share|improve this answer















    Use Collectors.mapping while groupingBy, for more information look at this doc-with-example



    Map<String, List<String>> conf = stream.    
    collect(Collectors.groupingBy(s -> s.split("=")[0], Collectors.mapping(v->v.split("=")[1], Collectors.toList())));

    System.out.println(conf); //{A=[groupA1, groupA2, groupA3], B=[groupB1, groupB2]}






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 3 hours ago

























    answered 3 hours ago









    DeadpoolDeadpool

    5,1822528




    5,1822528








    • 1





      That is exactly what I was looking for! Map<String, List<String>> conf = stream.collect(Collectors.groupingBy(s -> s.split("=")[0], Collectors.mapping(v->v.split("=")[1], Collectors.toList()))); and the output: KEY: A VALUE: groupA1 VALUE: groupA2 VALUE: groupA3 KEY: B VALUE: groupB1 VALUE: groupB2

      – BartD
      3 hours ago
















    • 1





      That is exactly what I was looking for! Map<String, List<String>> conf = stream.collect(Collectors.groupingBy(s -> s.split("=")[0], Collectors.mapping(v->v.split("=")[1], Collectors.toList()))); and the output: KEY: A VALUE: groupA1 VALUE: groupA2 VALUE: groupA3 KEY: B VALUE: groupB1 VALUE: groupB2

      – BartD
      3 hours ago










    1




    1





    That is exactly what I was looking for! Map<String, List<String>> conf = stream.collect(Collectors.groupingBy(s -> s.split("=")[0], Collectors.mapping(v->v.split("=")[1], Collectors.toList()))); and the output: KEY: A VALUE: groupA1 VALUE: groupA2 VALUE: groupA3 KEY: B VALUE: groupB1 VALUE: groupB2

    – BartD
    3 hours ago







    That is exactly what I was looking for! Map<String, List<String>> conf = stream.collect(Collectors.groupingBy(s -> s.split("=")[0], Collectors.mapping(v->v.split("=")[1], Collectors.toList()))); and the output: KEY: A VALUE: groupA1 VALUE: groupA2 VALUE: groupA3 KEY: B VALUE: groupB1 VALUE: groupB2

    – BartD
    3 hours ago













    0














    If you are open to using a third-party library, the following will work using Eclipse Collections.



    ListMultimap<String, String> strings = stream
    .map(s -> s.split("="))
    .collect(Collectors2.toListMultimap(a -> a[0], a -> a[1]));


    Collectors2.toListMultimap takes a Function to calculate the key and a separate Function to calculate the value. The ListMultimap<K, V> type is equivalent to Map<K, List<V>>.



    Note: I am a committer for Eclipse Collections.






    share|improve this answer




























      0














      If you are open to using a third-party library, the following will work using Eclipse Collections.



      ListMultimap<String, String> strings = stream
      .map(s -> s.split("="))
      .collect(Collectors2.toListMultimap(a -> a[0], a -> a[1]));


      Collectors2.toListMultimap takes a Function to calculate the key and a separate Function to calculate the value. The ListMultimap<K, V> type is equivalent to Map<K, List<V>>.



      Note: I am a committer for Eclipse Collections.






      share|improve this answer


























        0












        0








        0







        If you are open to using a third-party library, the following will work using Eclipse Collections.



        ListMultimap<String, String> strings = stream
        .map(s -> s.split("="))
        .collect(Collectors2.toListMultimap(a -> a[0], a -> a[1]));


        Collectors2.toListMultimap takes a Function to calculate the key and a separate Function to calculate the value. The ListMultimap<K, V> type is equivalent to Map<K, List<V>>.



        Note: I am a committer for Eclipse Collections.






        share|improve this answer













        If you are open to using a third-party library, the following will work using Eclipse Collections.



        ListMultimap<String, String> strings = stream
        .map(s -> s.split("="))
        .collect(Collectors2.toListMultimap(a -> a[0], a -> a[1]));


        Collectors2.toListMultimap takes a Function to calculate the key and a separate Function to calculate the value. The ListMultimap<K, V> type is equivalent to Map<K, List<V>>.



        Note: I am a committer for Eclipse Collections.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 20 mins ago









        Donald RaabDonald Raab

        4,26112029




        4,26112029






















            BartD is a new contributor. Be nice, and check out our Code of Conduct.










            draft saved

            draft discarded


















            BartD is a new contributor. Be nice, and check out our Code of Conduct.













            BartD is a new contributor. Be nice, and check out our Code of Conduct.












            BartD is a new contributor. Be nice, and check out our Code of Conduct.
















            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54383490%2fconverting-a-text-file-to-mapstring-liststring-using-lambda%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to label and detect the document text images

            Vallis Paradisi

            Tabula Rosettana