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












13















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




















  • 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
    Jan 26 at 22:47
















13















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




















  • 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
    Jan 26 at 22:47














13












13








13


3






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
















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















share|improve this question













share|improve this question




share|improve this question








edited Jan 26 at 23:06









Deadpool

6,5392629




6,5392629










asked Jan 26 at 22:43









BartDBartD

685




685








  • 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
    Jan 26 at 22:47














  • 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
    Jan 26 at 22:47








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
Jan 26 at 22:47





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
Jan 26 at 22:47












3 Answers
3






active

oldest

votes


















10














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


























  • 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
    Jan 26 at 23:35



















5














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
    Jan 26 at 23:12





















2














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


    }
    });














    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









    10














    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


























    • 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
      Jan 26 at 23:35
















    10














    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


























    • 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
      Jan 26 at 23:35














    10












    10








    10







    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 Jan 26 at 23:34

























    answered Jan 26 at 23:15









    Michał ZioberMichał Ziober

    14.9k1068105




    14.9k1068105













    • 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
      Jan 26 at 23:35



















    • 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
      Jan 26 at 23:35

















    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
    Jan 26 at 23:35





    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
    Jan 26 at 23:35













    5














    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
      Jan 26 at 23:12


















    5














    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
      Jan 26 at 23:12
















    5












    5








    5







    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 Jan 26 at 23:12

























    answered Jan 26 at 23:04









    DeadpoolDeadpool

    6,5392629




    6,5392629








    • 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
      Jan 26 at 23:12
















    • 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
      Jan 26 at 23:12










    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
    Jan 26 at 23:12







    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
    Jan 26 at 23:12













    2














    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




























      2














      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


























        2












        2








        2







        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 Jan 27 at 2:17









        Donald RaabDonald Raab

        4,33112030




        4,33112030






























            draft saved

            draft discarded




















































            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

            Human spaceflight

            Can not write log (Is /dev/pts mounted?) - openpty in Ubuntu-on-Windows?

            張江高科駅