Java 8 Split String and Create Map inside MapIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?Create ArrayList from arrayHow do I iterate over the words of a string?How do I read / convert an InputStream into a String in Java?How do I split a string on a delimiter in Bash?How to split a string in JavaHow do I convert a String to an int in Java?Creating a memory leak with JavaJava 8 List<V> into Map<K, V>

Notepad++ delete until colon for every line with replace all

What's the meaning of "Sollensaussagen"?

How to show a landlord what we have in savings?

Can compressed videos be decoded back to their uncompresed original format?

Processor speed limited at 0.4 Ghz

Is this draw by repetition?

What do you call someone who asks many questions?

How to stretch the corners of this image so that it looks like a perfect rectangle?

What does the same-ish mean?

What reasons are there for a Capitalist to oppose a 100% inheritance tax?

Can a virus destroy the BIOS of a modern computer?

Why is it a bad idea to hire a hitman to eliminate most corrupt politicians?

Finding the reason behind the value of the integral.

Send out email when Apex Queueable fails and test it

Theorists sure want true answers to this!

Fair gambler's ruin problem intuition

How to travel to Japan while expressing milk?

Why do I get negative height?

How to install cross-compiler on Ubuntu 18.04?

Knowledge-based authentication using Domain-driven Design in C#

GFCI outlets - can they be repaired? Are they really needed at the end of a circuit?

Where would I need my direct neural interface to be implanted?

Does int main() need a declaration on C++?

Do Iron Man suits sport waste management systems?



Java 8 Split String and Create Map inside Map


Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?Create ArrayList from arrayHow do I iterate over the words of a string?How do I read / convert an InputStream into a String in Java?How do I split a string on a delimiter in Bash?How to split a string in JavaHow do I convert a String to an int in Java?Creating a memory leak with JavaJava 8 List<V> into Map<K, V>













5















I have a String like 101-1-5,101-2-4,102-1-5,102-2-5,102-3-5,103-1-4.



I want to add this in to a Map<String, Map<String, String>>.



Like: 101=1=5, 2=4, 102=1=5, 2=5, 3=5, 103=1=4



How to do this using Java 8 stream?



I tried using normal Java. And it works fine.



public class Util 
public static void main(String[] args)

String samp = "101-1-5,101-2-4,102-1-5,102-2-5,102-3-5,103-1-4";

Map<String, Map<String, String>> m1 = new HashMap<>();
Map<String, String> m2 = null;

String[] items = samp.split(",");

for(int i=0; i<items.length; i++) m2==null)
m2 = new HashMap<>();

m2.put(subitem[1], subitem[2]);
m1.put(subitem[0], m2);

System.out.println(m1);











share|improve this question




























    5















    I have a String like 101-1-5,101-2-4,102-1-5,102-2-5,102-3-5,103-1-4.



    I want to add this in to a Map<String, Map<String, String>>.



    Like: 101=1=5, 2=4, 102=1=5, 2=5, 3=5, 103=1=4



    How to do this using Java 8 stream?



    I tried using normal Java. And it works fine.



    public class Util 
    public static void main(String[] args)

    String samp = "101-1-5,101-2-4,102-1-5,102-2-5,102-3-5,103-1-4";

    Map<String, Map<String, String>> m1 = new HashMap<>();
    Map<String, String> m2 = null;

    String[] items = samp.split(",");

    for(int i=0; i<items.length; i++) m2==null)
    m2 = new HashMap<>();

    m2.put(subitem[1], subitem[2]);
    m1.put(subitem[0], m2);

    System.out.println(m1);











    share|improve this question


























      5












      5








      5


      2






      I have a String like 101-1-5,101-2-4,102-1-5,102-2-5,102-3-5,103-1-4.



      I want to add this in to a Map<String, Map<String, String>>.



      Like: 101=1=5, 2=4, 102=1=5, 2=5, 3=5, 103=1=4



      How to do this using Java 8 stream?



      I tried using normal Java. And it works fine.



      public class Util 
      public static void main(String[] args)

      String samp = "101-1-5,101-2-4,102-1-5,102-2-5,102-3-5,103-1-4";

      Map<String, Map<String, String>> m1 = new HashMap<>();
      Map<String, String> m2 = null;

      String[] items = samp.split(",");

      for(int i=0; i<items.length; i++) m2==null)
      m2 = new HashMap<>();

      m2.put(subitem[1], subitem[2]);
      m1.put(subitem[0], m2);

      System.out.println(m1);











      share|improve this question
















      I have a String like 101-1-5,101-2-4,102-1-5,102-2-5,102-3-5,103-1-4.



      I want to add this in to a Map<String, Map<String, String>>.



      Like: 101=1=5, 2=4, 102=1=5, 2=5, 3=5, 103=1=4



      How to do this using Java 8 stream?



      I tried using normal Java. And it works fine.



      public class Util 
      public static void main(String[] args)

      String samp = "101-1-5,101-2-4,102-1-5,102-2-5,102-3-5,103-1-4";

      Map<String, Map<String, String>> m1 = new HashMap<>();
      Map<String, String> m2 = null;

      String[] items = samp.split(",");

      for(int i=0; i<items.length; i++) m2==null)
      m2 = new HashMap<>();

      m2.put(subitem[1], subitem[2]);
      m1.put(subitem[0], m2);

      System.out.println(m1);








      java split java-8 java-stream






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 21 at 23:46









      Samuel Philipp

      3,5541629




      3,5541629










      asked Mar 21 at 20:34









      ShakthiShakthi

      204317




      204317






















          2 Answers
          2






          active

          oldest

          votes


















          5














          You can use the following snippet for this:



          Map<String, Map<String, String>> result = Arrays.stream(samp.split(","))
          .map(i -> i.split("-"))
          .collect(Collectors.groupingBy(a -> a[0], Collectors.toMap(a -> a[1], a -> a[2])));


          First it creates a Stream of your items, which are mapped to a stream of arrays, containing the subitems. At the end you collect all by using group by on the first subitem and create an inner map with the second value as key and the last one as value.



          The result is:



          101=1=5, 2=4, 102=1=5, 2=5, 3=5, 103=1=4





          share|improve this answer
































            4














            Map<String, Map<String, String>> map = Arrays.stream(samp.split(","))
            .map(s -> s.split("-"))
            .collect(Collectors.toMap(
            o -> o[0],
            o -> Map.of(o[1], o[2]),
            (m1, m2) -> Stream.concat(m1.entrySet().stream(), m2.entrySet().stream())
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))));


            Map.of is from Java 9, you can use AbstractMap.SimpleEntry if you are on Java 8.



            Samuel's answer is better though, much concise.






            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%2f55288838%2fjava-8-split-string-and-create-map-inside-map%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              5














              You can use the following snippet for this:



              Map<String, Map<String, String>> result = Arrays.stream(samp.split(","))
              .map(i -> i.split("-"))
              .collect(Collectors.groupingBy(a -> a[0], Collectors.toMap(a -> a[1], a -> a[2])));


              First it creates a Stream of your items, which are mapped to a stream of arrays, containing the subitems. At the end you collect all by using group by on the first subitem and create an inner map with the second value as key and the last one as value.



              The result is:



              101=1=5, 2=4, 102=1=5, 2=5, 3=5, 103=1=4





              share|improve this answer





























                5














                You can use the following snippet for this:



                Map<String, Map<String, String>> result = Arrays.stream(samp.split(","))
                .map(i -> i.split("-"))
                .collect(Collectors.groupingBy(a -> a[0], Collectors.toMap(a -> a[1], a -> a[2])));


                First it creates a Stream of your items, which are mapped to a stream of arrays, containing the subitems. At the end you collect all by using group by on the first subitem and create an inner map with the second value as key and the last one as value.



                The result is:



                101=1=5, 2=4, 102=1=5, 2=5, 3=5, 103=1=4





                share|improve this answer



























                  5












                  5








                  5







                  You can use the following snippet for this:



                  Map<String, Map<String, String>> result = Arrays.stream(samp.split(","))
                  .map(i -> i.split("-"))
                  .collect(Collectors.groupingBy(a -> a[0], Collectors.toMap(a -> a[1], a -> a[2])));


                  First it creates a Stream of your items, which are mapped to a stream of arrays, containing the subitems. At the end you collect all by using group by on the first subitem and create an inner map with the second value as key and the last one as value.



                  The result is:



                  101=1=5, 2=4, 102=1=5, 2=5, 3=5, 103=1=4





                  share|improve this answer















                  You can use the following snippet for this:



                  Map<String, Map<String, String>> result = Arrays.stream(samp.split(","))
                  .map(i -> i.split("-"))
                  .collect(Collectors.groupingBy(a -> a[0], Collectors.toMap(a -> a[1], a -> a[2])));


                  First it creates a Stream of your items, which are mapped to a stream of arrays, containing the subitems. At the end you collect all by using group by on the first subitem and create an inner map with the second value as key and the last one as value.



                  The result is:



                  101=1=5, 2=4, 102=1=5, 2=5, 3=5, 103=1=4






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 23 at 11:06









                  marc_s

                  584k13011241270




                  584k13011241270










                  answered Mar 21 at 22:53









                  Samuel PhilippSamuel Philipp

                  3,5541629




                  3,5541629























                      4














                      Map<String, Map<String, String>> map = Arrays.stream(samp.split(","))
                      .map(s -> s.split("-"))
                      .collect(Collectors.toMap(
                      o -> o[0],
                      o -> Map.of(o[1], o[2]),
                      (m1, m2) -> Stream.concat(m1.entrySet().stream(), m2.entrySet().stream())
                      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))));


                      Map.of is from Java 9, you can use AbstractMap.SimpleEntry if you are on Java 8.



                      Samuel's answer is better though, much concise.






                      share|improve this answer





























                        4














                        Map<String, Map<String, String>> map = Arrays.stream(samp.split(","))
                        .map(s -> s.split("-"))
                        .collect(Collectors.toMap(
                        o -> o[0],
                        o -> Map.of(o[1], o[2]),
                        (m1, m2) -> Stream.concat(m1.entrySet().stream(), m2.entrySet().stream())
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))));


                        Map.of is from Java 9, you can use AbstractMap.SimpleEntry if you are on Java 8.



                        Samuel's answer is better though, much concise.






                        share|improve this answer



























                          4












                          4








                          4







                          Map<String, Map<String, String>> map = Arrays.stream(samp.split(","))
                          .map(s -> s.split("-"))
                          .collect(Collectors.toMap(
                          o -> o[0],
                          o -> Map.of(o[1], o[2]),
                          (m1, m2) -> Stream.concat(m1.entrySet().stream(), m2.entrySet().stream())
                          .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))));


                          Map.of is from Java 9, you can use AbstractMap.SimpleEntry if you are on Java 8.



                          Samuel's answer is better though, much concise.






                          share|improve this answer















                          Map<String, Map<String, String>> map = Arrays.stream(samp.split(","))
                          .map(s -> s.split("-"))
                          .collect(Collectors.toMap(
                          o -> o[0],
                          o -> Map.of(o[1], o[2]),
                          (m1, m2) -> Stream.concat(m1.entrySet().stream(), m2.entrySet().stream())
                          .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))));


                          Map.of is from Java 9, you can use AbstractMap.SimpleEntry if you are on Java 8.



                          Samuel's answer is better though, much concise.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Mar 21 at 23:03

























                          answered Mar 21 at 22:50









                          KartikKartik

                          4,49431537




                          4,49431537



























                              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%2f55288838%2fjava-8-split-string-and-create-map-inside-map%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

                              Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                              SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                              은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현