Java 8 streams - merge a collection of Maps2019 Community Moderator ElectionIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?A Java collection of value pairs? (tuples?)How do I convert a String to an int in Java?Creating a memory leak with JavaJava 8 List<V> into Map<K, V>How to Convert a Java 8 Stream to an Array?

Is this Pascal's Matrix?

Turning a hard to access nut?

What will the Frenchman say?

Homology of the fiber

Recursively updating the MLE as new observations stream in

How old is Nick Fury?

What are the rules for concealing thieves' tools (or items in general)?

Have any astronauts/cosmonauts died in space?

Why is indicated airspeed rather than ground speed used during the takeoff roll?

Why are there no stars visible in cislunar space?

Fair way to split coins

Error in master's thesis, I do not know what to do

What (if any) is the reason to buy in small local stores?

If I cast the Enlarge/Reduce spell on an arrow, what weapon could it count as?

Are hand made posters acceptable in Academia?

Why is this tree refusing to shed its dead leaves?

Animating wave motion in water

Can "few" be used as a subject? If so, what is the rule?

pipe commands inside find -exec?

Why I don't get the wanted width of tcbox?

Why is participating in the European Parliamentary elections used as a threat?

What is the reasoning behind standardization (dividing by standard deviation)?

Do I need to convey a moral for each of my blog post?

Do people actually use the word "kaputt" in conversation?



Java 8 streams - merge a collection of Maps



2019 Community Moderator ElectionIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?A Java collection of value pairs? (tuples?)How do I convert a String to an int in Java?Creating a memory leak with JavaJava 8 List<V> into Map<K, V>How to Convert a Java 8 Stream to an Array?










2















Lets say I have a method with a following signature:



Map<String, String> merge (String[][] ... maps)


It takes a (variadic) number of two-dim arrays which represent mappings, for example:



 String[][] m1 = new String[][] 
"k1", "a",
"k2", "b"
;

String[][] m2 = new String[][]
"k1", "a",
"k2", "b",
"k3", "c"
;

String[][] m3 = new String[][]
"k1", "x",
"k2", "b"
;


Now I can merge any two of the maps left-to-right like this:



 Map<String, String> m1 = Stream.of(map1).collect(Collectors.toMap(k -> k[0], v -> v[1]));
Map<String, String> m2 = Stream.of(map2).collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null")));
m1.forEach((key, value) -> m2.merge(key, value, (v1, v2) -> v1));


But how can I go about merging a variadic number of such array-maps, so that after passing m1, m2, m3 as defined above the result is:



 String[][] m3 = new String[][] 
"k1", "x",
"k2", "b"
"k3", "c"
;









share|improve this question


























    2















    Lets say I have a method with a following signature:



    Map<String, String> merge (String[][] ... maps)


    It takes a (variadic) number of two-dim arrays which represent mappings, for example:



     String[][] m1 = new String[][] 
    "k1", "a",
    "k2", "b"
    ;

    String[][] m2 = new String[][]
    "k1", "a",
    "k2", "b",
    "k3", "c"
    ;

    String[][] m3 = new String[][]
    "k1", "x",
    "k2", "b"
    ;


    Now I can merge any two of the maps left-to-right like this:



     Map<String, String> m1 = Stream.of(map1).collect(Collectors.toMap(k -> k[0], v -> v[1]));
    Map<String, String> m2 = Stream.of(map2).collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null")));
    m1.forEach((key, value) -> m2.merge(key, value, (v1, v2) -> v1));


    But how can I go about merging a variadic number of such array-maps, so that after passing m1, m2, m3 as defined above the result is:



     String[][] m3 = new String[][] 
    "k1", "x",
    "k2", "b"
    "k3", "c"
    ;









    share|improve this question
























      2












      2








      2


      1






      Lets say I have a method with a following signature:



      Map<String, String> merge (String[][] ... maps)


      It takes a (variadic) number of two-dim arrays which represent mappings, for example:



       String[][] m1 = new String[][] 
      "k1", "a",
      "k2", "b"
      ;

      String[][] m2 = new String[][]
      "k1", "a",
      "k2", "b",
      "k3", "c"
      ;

      String[][] m3 = new String[][]
      "k1", "x",
      "k2", "b"
      ;


      Now I can merge any two of the maps left-to-right like this:



       Map<String, String> m1 = Stream.of(map1).collect(Collectors.toMap(k -> k[0], v -> v[1]));
      Map<String, String> m2 = Stream.of(map2).collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null")));
      m1.forEach((key, value) -> m2.merge(key, value, (v1, v2) -> v1));


      But how can I go about merging a variadic number of such array-maps, so that after passing m1, m2, m3 as defined above the result is:



       String[][] m3 = new String[][] 
      "k1", "x",
      "k2", "b"
      "k3", "c"
      ;









      share|improve this question














      Lets say I have a method with a following signature:



      Map<String, String> merge (String[][] ... maps)


      It takes a (variadic) number of two-dim arrays which represent mappings, for example:



       String[][] m1 = new String[][] 
      "k1", "a",
      "k2", "b"
      ;

      String[][] m2 = new String[][]
      "k1", "a",
      "k2", "b",
      "k3", "c"
      ;

      String[][] m3 = new String[][]
      "k1", "x",
      "k2", "b"
      ;


      Now I can merge any two of the maps left-to-right like this:



       Map<String, String> m1 = Stream.of(map1).collect(Collectors.toMap(k -> k[0], v -> v[1]));
      Map<String, String> m2 = Stream.of(map2).collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null")));
      m1.forEach((key, value) -> m2.merge(key, value, (v1, v2) -> v1));


      But how can I go about merging a variadic number of such array-maps, so that after passing m1, m2, m3 as defined above the result is:



       String[][] m3 = new String[][] 
      "k1", "x",
      "k2", "b"
      "k3", "c"
      ;






      java java-8 java-stream






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 6 at 23:22









      fbielejecfbielejec

      1,23531630




      1,23531630






















          2 Answers
          2






          active

          oldest

          votes


















          6














          It's quite simple, if I'm understanding your question correctly. You just flatMap all the entries and collect to map, with a merge function that selects the later value:



          Map<String, String> merge (String[][] ... maps) 
          return Arrays.stream(maps)
          .flatMap(Arrays::stream)
          .collect(Collectors.toMap(a -> a[0], a -> a[1], (a, b) -> b));



          If you want to convert it back to an array, you can do



          String[][] m3 = merge(maps)
          .entrySet()
          .stream()
          .map(e -> new String[] e.getKey(), e.getValue() )
          .toArray(String[][]::new);





          share|improve this answer

























          • Quite nice, I just added some null punning, for safety return Arrays.stream(maps) .flatMap(Arrays::stream) .collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null"), (v1, v2) -> v2));

            – fbielejec
            Mar 7 at 9:35






          • 2





            @fbielejec instead of Optional.ofNullable(v[1]).orElse("null") you can simply use String.valueOf(v[1]). Even v[1] == null? "null": v[1] is simpler…

            – Holger
            Mar 7 at 13:40












          • Yes indeed, thank you. Bit of context: these are then passed to logging and used as meta information (serialized to JSON) This can throw npe in some edge cases, hence the extra protection.

            – fbielejec
            Mar 7 at 17:55


















          3














          Map<String, String> merge(String[][]... maps) 
          return Stream.of(maps)
          .flatMap(Arrays::stream) //flatten all maps into a single stream
          .map(s -> Map.entry(s[0], s[1])) //convert array to Entry
          .collect(Collectors.toMap(Map.Entry::getKey,
          Map.Entry::getValue,
          (o1, o2) -> o2));



          Edit: No need to convert to Entry. We can directly collect to map as @shmosel showed.






          share|improve this answer




















          • 2





            Worth noting that Map.entry exists from Java 9 onwards

            – LppEdd
            Mar 6 at 23:36






          • 1





            @LppEdd and doesn’t support null values. Which seems to be an issue for the OP.

            – Holger
            Mar 7 at 13:42











          • @Holger SimpleEntry to the rescue. Although it's not needed at all as Kartik pointed out.

            – LppEdd
            Mar 7 at 14:22











          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%2f55033758%2fjava-8-streams-merge-a-collection-of-maps%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









          6














          It's quite simple, if I'm understanding your question correctly. You just flatMap all the entries and collect to map, with a merge function that selects the later value:



          Map<String, String> merge (String[][] ... maps) 
          return Arrays.stream(maps)
          .flatMap(Arrays::stream)
          .collect(Collectors.toMap(a -> a[0], a -> a[1], (a, b) -> b));



          If you want to convert it back to an array, you can do



          String[][] m3 = merge(maps)
          .entrySet()
          .stream()
          .map(e -> new String[] e.getKey(), e.getValue() )
          .toArray(String[][]::new);





          share|improve this answer

























          • Quite nice, I just added some null punning, for safety return Arrays.stream(maps) .flatMap(Arrays::stream) .collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null"), (v1, v2) -> v2));

            – fbielejec
            Mar 7 at 9:35






          • 2





            @fbielejec instead of Optional.ofNullable(v[1]).orElse("null") you can simply use String.valueOf(v[1]). Even v[1] == null? "null": v[1] is simpler…

            – Holger
            Mar 7 at 13:40












          • Yes indeed, thank you. Bit of context: these are then passed to logging and used as meta information (serialized to JSON) This can throw npe in some edge cases, hence the extra protection.

            – fbielejec
            Mar 7 at 17:55















          6














          It's quite simple, if I'm understanding your question correctly. You just flatMap all the entries and collect to map, with a merge function that selects the later value:



          Map<String, String> merge (String[][] ... maps) 
          return Arrays.stream(maps)
          .flatMap(Arrays::stream)
          .collect(Collectors.toMap(a -> a[0], a -> a[1], (a, b) -> b));



          If you want to convert it back to an array, you can do



          String[][] m3 = merge(maps)
          .entrySet()
          .stream()
          .map(e -> new String[] e.getKey(), e.getValue() )
          .toArray(String[][]::new);





          share|improve this answer

























          • Quite nice, I just added some null punning, for safety return Arrays.stream(maps) .flatMap(Arrays::stream) .collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null"), (v1, v2) -> v2));

            – fbielejec
            Mar 7 at 9:35






          • 2





            @fbielejec instead of Optional.ofNullable(v[1]).orElse("null") you can simply use String.valueOf(v[1]). Even v[1] == null? "null": v[1] is simpler…

            – Holger
            Mar 7 at 13:40












          • Yes indeed, thank you. Bit of context: these are then passed to logging and used as meta information (serialized to JSON) This can throw npe in some edge cases, hence the extra protection.

            – fbielejec
            Mar 7 at 17:55













          6












          6








          6







          It's quite simple, if I'm understanding your question correctly. You just flatMap all the entries and collect to map, with a merge function that selects the later value:



          Map<String, String> merge (String[][] ... maps) 
          return Arrays.stream(maps)
          .flatMap(Arrays::stream)
          .collect(Collectors.toMap(a -> a[0], a -> a[1], (a, b) -> b));



          If you want to convert it back to an array, you can do



          String[][] m3 = merge(maps)
          .entrySet()
          .stream()
          .map(e -> new String[] e.getKey(), e.getValue() )
          .toArray(String[][]::new);





          share|improve this answer















          It's quite simple, if I'm understanding your question correctly. You just flatMap all the entries and collect to map, with a merge function that selects the later value:



          Map<String, String> merge (String[][] ... maps) 
          return Arrays.stream(maps)
          .flatMap(Arrays::stream)
          .collect(Collectors.toMap(a -> a[0], a -> a[1], (a, b) -> b));



          If you want to convert it back to an array, you can do



          String[][] m3 = merge(maps)
          .entrySet()
          .stream()
          .map(e -> new String[] e.getKey(), e.getValue() )
          .toArray(String[][]::new);






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 6 at 23:54

























          answered Mar 6 at 23:38









          shmoselshmosel

          36.8k43996




          36.8k43996












          • Quite nice, I just added some null punning, for safety return Arrays.stream(maps) .flatMap(Arrays::stream) .collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null"), (v1, v2) -> v2));

            – fbielejec
            Mar 7 at 9:35






          • 2





            @fbielejec instead of Optional.ofNullable(v[1]).orElse("null") you can simply use String.valueOf(v[1]). Even v[1] == null? "null": v[1] is simpler…

            – Holger
            Mar 7 at 13:40












          • Yes indeed, thank you. Bit of context: these are then passed to logging and used as meta information (serialized to JSON) This can throw npe in some edge cases, hence the extra protection.

            – fbielejec
            Mar 7 at 17:55

















          • Quite nice, I just added some null punning, for safety return Arrays.stream(maps) .flatMap(Arrays::stream) .collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null"), (v1, v2) -> v2));

            – fbielejec
            Mar 7 at 9:35






          • 2





            @fbielejec instead of Optional.ofNullable(v[1]).orElse("null") you can simply use String.valueOf(v[1]). Even v[1] == null? "null": v[1] is simpler…

            – Holger
            Mar 7 at 13:40












          • Yes indeed, thank you. Bit of context: these are then passed to logging and used as meta information (serialized to JSON) This can throw npe in some edge cases, hence the extra protection.

            – fbielejec
            Mar 7 at 17:55
















          Quite nice, I just added some null punning, for safety return Arrays.stream(maps) .flatMap(Arrays::stream) .collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null"), (v1, v2) -> v2));

          – fbielejec
          Mar 7 at 9:35





          Quite nice, I just added some null punning, for safety return Arrays.stream(maps) .flatMap(Arrays::stream) .collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null"), (v1, v2) -> v2));

          – fbielejec
          Mar 7 at 9:35




          2




          2





          @fbielejec instead of Optional.ofNullable(v[1]).orElse("null") you can simply use String.valueOf(v[1]). Even v[1] == null? "null": v[1] is simpler…

          – Holger
          Mar 7 at 13:40






          @fbielejec instead of Optional.ofNullable(v[1]).orElse("null") you can simply use String.valueOf(v[1]). Even v[1] == null? "null": v[1] is simpler…

          – Holger
          Mar 7 at 13:40














          Yes indeed, thank you. Bit of context: these are then passed to logging and used as meta information (serialized to JSON) This can throw npe in some edge cases, hence the extra protection.

          – fbielejec
          Mar 7 at 17:55





          Yes indeed, thank you. Bit of context: these are then passed to logging and used as meta information (serialized to JSON) This can throw npe in some edge cases, hence the extra protection.

          – fbielejec
          Mar 7 at 17:55













          3














          Map<String, String> merge(String[][]... maps) 
          return Stream.of(maps)
          .flatMap(Arrays::stream) //flatten all maps into a single stream
          .map(s -> Map.entry(s[0], s[1])) //convert array to Entry
          .collect(Collectors.toMap(Map.Entry::getKey,
          Map.Entry::getValue,
          (o1, o2) -> o2));



          Edit: No need to convert to Entry. We can directly collect to map as @shmosel showed.






          share|improve this answer




















          • 2





            Worth noting that Map.entry exists from Java 9 onwards

            – LppEdd
            Mar 6 at 23:36






          • 1





            @LppEdd and doesn’t support null values. Which seems to be an issue for the OP.

            – Holger
            Mar 7 at 13:42











          • @Holger SimpleEntry to the rescue. Although it's not needed at all as Kartik pointed out.

            – LppEdd
            Mar 7 at 14:22
















          3














          Map<String, String> merge(String[][]... maps) 
          return Stream.of(maps)
          .flatMap(Arrays::stream) //flatten all maps into a single stream
          .map(s -> Map.entry(s[0], s[1])) //convert array to Entry
          .collect(Collectors.toMap(Map.Entry::getKey,
          Map.Entry::getValue,
          (o1, o2) -> o2));



          Edit: No need to convert to Entry. We can directly collect to map as @shmosel showed.






          share|improve this answer




















          • 2





            Worth noting that Map.entry exists from Java 9 onwards

            – LppEdd
            Mar 6 at 23:36






          • 1





            @LppEdd and doesn’t support null values. Which seems to be an issue for the OP.

            – Holger
            Mar 7 at 13:42











          • @Holger SimpleEntry to the rescue. Although it's not needed at all as Kartik pointed out.

            – LppEdd
            Mar 7 at 14:22














          3












          3








          3







          Map<String, String> merge(String[][]... maps) 
          return Stream.of(maps)
          .flatMap(Arrays::stream) //flatten all maps into a single stream
          .map(s -> Map.entry(s[0], s[1])) //convert array to Entry
          .collect(Collectors.toMap(Map.Entry::getKey,
          Map.Entry::getValue,
          (o1, o2) -> o2));



          Edit: No need to convert to Entry. We can directly collect to map as @shmosel showed.






          share|improve this answer















          Map<String, String> merge(String[][]... maps) 
          return Stream.of(maps)
          .flatMap(Arrays::stream) //flatten all maps into a single stream
          .map(s -> Map.entry(s[0], s[1])) //convert array to Entry
          .collect(Collectors.toMap(Map.Entry::getKey,
          Map.Entry::getValue,
          (o1, o2) -> o2));



          Edit: No need to convert to Entry. We can directly collect to map as @shmosel showed.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 6 at 23:36

























          answered Mar 6 at 23:34









          KartikKartik

          4,19731537




          4,19731537







          • 2





            Worth noting that Map.entry exists from Java 9 onwards

            – LppEdd
            Mar 6 at 23:36






          • 1





            @LppEdd and doesn’t support null values. Which seems to be an issue for the OP.

            – Holger
            Mar 7 at 13:42











          • @Holger SimpleEntry to the rescue. Although it's not needed at all as Kartik pointed out.

            – LppEdd
            Mar 7 at 14:22













          • 2





            Worth noting that Map.entry exists from Java 9 onwards

            – LppEdd
            Mar 6 at 23:36






          • 1





            @LppEdd and doesn’t support null values. Which seems to be an issue for the OP.

            – Holger
            Mar 7 at 13:42











          • @Holger SimpleEntry to the rescue. Although it's not needed at all as Kartik pointed out.

            – LppEdd
            Mar 7 at 14:22








          2




          2





          Worth noting that Map.entry exists from Java 9 onwards

          – LppEdd
          Mar 6 at 23:36





          Worth noting that Map.entry exists from Java 9 onwards

          – LppEdd
          Mar 6 at 23:36




          1




          1





          @LppEdd and doesn’t support null values. Which seems to be an issue for the OP.

          – Holger
          Mar 7 at 13:42





          @LppEdd and doesn’t support null values. Which seems to be an issue for the OP.

          – Holger
          Mar 7 at 13:42













          @Holger SimpleEntry to the rescue. Although it's not needed at all as Kartik pointed out.

          – LppEdd
          Mar 7 at 14:22






          @Holger SimpleEntry to the rescue. Although it's not needed at all as Kartik pointed out.

          – LppEdd
          Mar 7 at 14:22


















          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%2f55033758%2fjava-8-streams-merge-a-collection-of-maps%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

          1928 у кіно

          Захаров Федір Захарович

          Ель Греко