Is there a clean (and null safe) way to multiply the values of a map in Java?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
6
down vote

favorite












I have a Map<String, Double>, and want to multiply all the values in the map by 2, say, but keep the nulls as nulls.



I can obviously use a for loop to do this, but was wondering if there was a cleaner way to do so?



Map<String, Double> someMap = someMapFunction();
Map<String, Double> adjustedMap = new Hashmap<>();
if (someMap != null)
for (Map.Entry<String,Double> pair : someMap.entryset())
if (pair.getValue() == null)
adjustedMap.put(pair.getKey(), pair.getValue());
else
adjustedMap.put(pair.getKey(), pair.getValue()*2)






Also sometimes the map returned by someMapFunction is an immutable map, so this can't be done in place using Map.replaceAll. I couldn't come up with a stream solution that was cleaner










share|improve this question



























    up vote
    6
    down vote

    favorite












    I have a Map<String, Double>, and want to multiply all the values in the map by 2, say, but keep the nulls as nulls.



    I can obviously use a for loop to do this, but was wondering if there was a cleaner way to do so?



    Map<String, Double> someMap = someMapFunction();
    Map<String, Double> adjustedMap = new Hashmap<>();
    if (someMap != null)
    for (Map.Entry<String,Double> pair : someMap.entryset())
    if (pair.getValue() == null)
    adjustedMap.put(pair.getKey(), pair.getValue());
    else
    adjustedMap.put(pair.getKey(), pair.getValue()*2)






    Also sometimes the map returned by someMapFunction is an immutable map, so this can't be done in place using Map.replaceAll. I couldn't come up with a stream solution that was cleaner










    share|improve this question

























      up vote
      6
      down vote

      favorite









      up vote
      6
      down vote

      favorite











      I have a Map<String, Double>, and want to multiply all the values in the map by 2, say, but keep the nulls as nulls.



      I can obviously use a for loop to do this, but was wondering if there was a cleaner way to do so?



      Map<String, Double> someMap = someMapFunction();
      Map<String, Double> adjustedMap = new Hashmap<>();
      if (someMap != null)
      for (Map.Entry<String,Double> pair : someMap.entryset())
      if (pair.getValue() == null)
      adjustedMap.put(pair.getKey(), pair.getValue());
      else
      adjustedMap.put(pair.getKey(), pair.getValue()*2)






      Also sometimes the map returned by someMapFunction is an immutable map, so this can't be done in place using Map.replaceAll. I couldn't come up with a stream solution that was cleaner










      share|improve this question















      I have a Map<String, Double>, and want to multiply all the values in the map by 2, say, but keep the nulls as nulls.



      I can obviously use a for loop to do this, but was wondering if there was a cleaner way to do so?



      Map<String, Double> someMap = someMapFunction();
      Map<String, Double> adjustedMap = new Hashmap<>();
      if (someMap != null)
      for (Map.Entry<String,Double> pair : someMap.entryset())
      if (pair.getValue() == null)
      adjustedMap.put(pair.getKey(), pair.getValue());
      else
      adjustedMap.put(pair.getKey(), pair.getValue()*2)






      Also sometimes the map returned by someMapFunction is an immutable map, so this can't be done in place using Map.replaceAll. I couldn't come up with a stream solution that was cleaner







      java java-8 java-stream






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 27 mins ago









      Michael

      16.7k63066




      16.7k63066










      asked 44 mins ago









      Omar Haque

      1335




      1335






















          8 Answers
          8






          active

          oldest

          votes

















          up vote
          3
          down vote



          accepted










          As an alternative to streaming and/or copying solutions, the Maps.transformValues() utility method exists in Google Guava:



          Map<String, Double> adjustedMap = Maps.transformValues(someMap, value -> (value != null) ? (2 * value) : null);


          This returns a lazy view of the original map that does not do any work on its own, but applies the given function when needed. This can be both a pro (if you're unlikely to ever need all the values, this will save you some computing time) and a con (if you'll need the same value many times, or if you need to further change someMap without adjustedMap seeing the changes) depending on your usage.






          share|improve this answer



























            up vote
            8
            down vote













            You can create a copy of the original map and then call replaceAll:



            Map<String, Double> adjustedMap = new HashMap<>(someMap);
            adjustedMap.replaceAll ((k,v) -> v != null ? 2*v : null);





            share|improve this answer





























              up vote
              2
              down vote













              It can be done like that



              someMap.entrySet().stream()
              .filter(stringDoubleEntry -> stringDoubleEntry.getValue() != null) //filter null values out
              .forEach(stringDoubleEntry -> stringDoubleEntry.setValue(stringDoubleEntry.getValue() * 2)); //multiply values which are not null


              In case you need a second map where just values in which are not null just use the forEach to put them into your new map.






              share|improve this answer
















              • 1




                This solution does what the OP's code does in a nice form (though stringDoubleEntry is a bit unaccustomedly long). It exploits that the entries are backed by the map; no new map is created.
                – Joop Eggen
                17 mins ago






              • 1




                I did not want to criticize, indeed the other way around. There was no upvote and others were already upvoted, despite your solution being straight-forward efficient.
                – Joop Eggen
                12 mins ago










              • My mistake I read over 2 words which were the key that was different haha.
                – CodeMatrix
                10 mins ago


















              up vote
              2
              down vote













              You can achieve that by converting into a stream, something like:



               someMap.entrySet()
              .forEach(entry ->
              if(entry.getValue() != null)
              adjustedMap.put(entry.getKey(), someMap.get(entry.getKey()) * 2);
              else
              adjustedMap.put(entry.getKey(), null);

              );


              which can be shorted to :



              someMap.forEach((key, value) -> 
              if (value != null)
              adjustedMap.put(key, value * 2);
              else
              adjustedMap.put(key, null);

              );


              So, if you'r having a map with:



              Map<String, Double> someMap = new HashMap<>();
              someMap.put("test1", 1d);
              someMap.put("test2", 2d);
              someMap.put("test3", 3d);
              someMap.put("testNull", null);
              someMap.put("test4", 4d);


              You will get this output:




              test4=8.0, test2=4.0, test3=6.0, testNull=null, test1=2.0







              share|improve this answer


















              • 3




                The OP wanted to "keep the nulls as nulls.", not filter them out.
                – Eran
                22 mins ago










              • @Eran My bad, i'm fixing, thanks
                – Leviand
                21 mins ago











              • @Eran fixed, thanks for pointing it
                – Leviand
                9 mins ago










              • Your someMap.get(key) can be simply value instead. Anyway, downvoting for style. It may be my personal subjective preference, but I strongly believe functional code should be side-effect free. Therefore, using forEach() on one map to change a different map is a no-no in my book. I'd prefer collecting the stream into a new map instead. That's the canonical and recognized way of consuming streams.
                – Petr Janeček
                3 mins ago

















              up vote
              1
              down vote













              Use like this.



               Map<String, Double> adjustedMap = map.entrySet().stream()filter(x -> x.getValue() != null)
              .collect(Collectors.toMap(x -> x.getKey(), x -> 2*x.getValue()));
              //printing
              adjustedMap.entrySet().stream().forEach(System.out::println);





              share|improve this answer






















              • This is not null safe
                – Eran
                26 mins ago

















              up vote
              1
              down vote













              You can do this with this code:



               Map<String, Double> map = new HashMap<>();
              map.put("1", 3.0);
              map.put("3", null);
              map.put("2", 5.0);

              Map<String, Double> res = map.entrySet().stream()
              .collect(HashMap::new, (m,v)->m.put(v.getKey(), v.getValue() != null ? v.getValue() * 2 : null), HashMap::putAll);

              System.out.println(res);


              and the output will be:




              1=6.0, 2=10.0, 3=null




              It will allow you to keep null values in the map.






              share|improve this answer





























                up vote
                1
                down vote













                To keep null values you can use something as simple as :



                someMap.keySet()
                .stream()
                .forEach(key -> adjustedMap.put(key, (someMap.get(key)) == null ? null : someMap.get(key) * 2));





                share|improve this answer




















                • You should absolutely stream on the entrySet(), they you'd avoid calling someMap.get(key) in a loop, and would be able to just do entry.value() instead. Anyway, downvoting for style. It may be my personal subjective preference, but I strongly believe functional code should be side-effect free. Therefore, using forEach() on one map to change a different map is a no-no in my book. I'd prefer collecting the stream into a new map instead. That's the canonical and recognized way of consuming streams.
                  – Petr Janeček
                  5 mins ago

















                up vote
                1
                down vote













                Try something like this with java 8 steam api



                Map<String, Double> newMap = oldMap.entrySet().stream()
                .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue() == null ? null: x.getValue()*2));





                share|improve this answer






















                • This will throw NullPointerException for any null values.
                  – Eran
                  24 mins ago










                • how is it possible ?
                  – oguzhan aygun
                  22 mins ago







                • 3




                  That's the behavior of Collectors.toMap. You can try it and see for yourself.
                  – Eran
                  20 mins ago










                • thank you Eran I just tried and learn something new :)
                  – oguzhan aygun
                  14 mins ago










                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',
                convertImagesToLinks: true,
                noModals: false,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                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%2f52850108%2fis-there-a-clean-and-null-safe-way-to-multiply-the-values-of-a-map-in-java%23new-answer', 'question_page');

                );

                Post as a guest






























                8 Answers
                8






                active

                oldest

                votes








                8 Answers
                8






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                3
                down vote



                accepted










                As an alternative to streaming and/or copying solutions, the Maps.transformValues() utility method exists in Google Guava:



                Map<String, Double> adjustedMap = Maps.transformValues(someMap, value -> (value != null) ? (2 * value) : null);


                This returns a lazy view of the original map that does not do any work on its own, but applies the given function when needed. This can be both a pro (if you're unlikely to ever need all the values, this will save you some computing time) and a con (if you'll need the same value many times, or if you need to further change someMap without adjustedMap seeing the changes) depending on your usage.






                share|improve this answer
























                  up vote
                  3
                  down vote



                  accepted










                  As an alternative to streaming and/or copying solutions, the Maps.transformValues() utility method exists in Google Guava:



                  Map<String, Double> adjustedMap = Maps.transformValues(someMap, value -> (value != null) ? (2 * value) : null);


                  This returns a lazy view of the original map that does not do any work on its own, but applies the given function when needed. This can be both a pro (if you're unlikely to ever need all the values, this will save you some computing time) and a con (if you'll need the same value many times, or if you need to further change someMap without adjustedMap seeing the changes) depending on your usage.






                  share|improve this answer






















                    up vote
                    3
                    down vote



                    accepted







                    up vote
                    3
                    down vote



                    accepted






                    As an alternative to streaming and/or copying solutions, the Maps.transformValues() utility method exists in Google Guava:



                    Map<String, Double> adjustedMap = Maps.transformValues(someMap, value -> (value != null) ? (2 * value) : null);


                    This returns a lazy view of the original map that does not do any work on its own, but applies the given function when needed. This can be both a pro (if you're unlikely to ever need all the values, this will save you some computing time) and a con (if you'll need the same value many times, or if you need to further change someMap without adjustedMap seeing the changes) depending on your usage.






                    share|improve this answer












                    As an alternative to streaming and/or copying solutions, the Maps.transformValues() utility method exists in Google Guava:



                    Map<String, Double> adjustedMap = Maps.transformValues(someMap, value -> (value != null) ? (2 * value) : null);


                    This returns a lazy view of the original map that does not do any work on its own, but applies the given function when needed. This can be both a pro (if you're unlikely to ever need all the values, this will save you some computing time) and a con (if you'll need the same value many times, or if you need to further change someMap without adjustedMap seeing the changes) depending on your usage.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered 14 mins ago









                    Petr Janeček

                    28.9k887122




                    28.9k887122






















                        up vote
                        8
                        down vote













                        You can create a copy of the original map and then call replaceAll:



                        Map<String, Double> adjustedMap = new HashMap<>(someMap);
                        adjustedMap.replaceAll ((k,v) -> v != null ? 2*v : null);





                        share|improve this answer


























                          up vote
                          8
                          down vote













                          You can create a copy of the original map and then call replaceAll:



                          Map<String, Double> adjustedMap = new HashMap<>(someMap);
                          adjustedMap.replaceAll ((k,v) -> v != null ? 2*v : null);





                          share|improve this answer
























                            up vote
                            8
                            down vote










                            up vote
                            8
                            down vote









                            You can create a copy of the original map and then call replaceAll:



                            Map<String, Double> adjustedMap = new HashMap<>(someMap);
                            adjustedMap.replaceAll ((k,v) -> v != null ? 2*v : null);





                            share|improve this answer














                            You can create a copy of the original map and then call replaceAll:



                            Map<String, Double> adjustedMap = new HashMap<>(someMap);
                            adjustedMap.replaceAll ((k,v) -> v != null ? 2*v : null);






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited 25 mins ago

























                            answered 36 mins ago









                            Eran

                            267k34409496




                            267k34409496




















                                up vote
                                2
                                down vote













                                It can be done like that



                                someMap.entrySet().stream()
                                .filter(stringDoubleEntry -> stringDoubleEntry.getValue() != null) //filter null values out
                                .forEach(stringDoubleEntry -> stringDoubleEntry.setValue(stringDoubleEntry.getValue() * 2)); //multiply values which are not null


                                In case you need a second map where just values in which are not null just use the forEach to put them into your new map.






                                share|improve this answer
















                                • 1




                                  This solution does what the OP's code does in a nice form (though stringDoubleEntry is a bit unaccustomedly long). It exploits that the entries are backed by the map; no new map is created.
                                  – Joop Eggen
                                  17 mins ago






                                • 1




                                  I did not want to criticize, indeed the other way around. There was no upvote and others were already upvoted, despite your solution being straight-forward efficient.
                                  – Joop Eggen
                                  12 mins ago










                                • My mistake I read over 2 words which were the key that was different haha.
                                  – CodeMatrix
                                  10 mins ago















                                up vote
                                2
                                down vote













                                It can be done like that



                                someMap.entrySet().stream()
                                .filter(stringDoubleEntry -> stringDoubleEntry.getValue() != null) //filter null values out
                                .forEach(stringDoubleEntry -> stringDoubleEntry.setValue(stringDoubleEntry.getValue() * 2)); //multiply values which are not null


                                In case you need a second map where just values in which are not null just use the forEach to put them into your new map.






                                share|improve this answer
















                                • 1




                                  This solution does what the OP's code does in a nice form (though stringDoubleEntry is a bit unaccustomedly long). It exploits that the entries are backed by the map; no new map is created.
                                  – Joop Eggen
                                  17 mins ago






                                • 1




                                  I did not want to criticize, indeed the other way around. There was no upvote and others were already upvoted, despite your solution being straight-forward efficient.
                                  – Joop Eggen
                                  12 mins ago










                                • My mistake I read over 2 words which were the key that was different haha.
                                  – CodeMatrix
                                  10 mins ago













                                up vote
                                2
                                down vote










                                up vote
                                2
                                down vote









                                It can be done like that



                                someMap.entrySet().stream()
                                .filter(stringDoubleEntry -> stringDoubleEntry.getValue() != null) //filter null values out
                                .forEach(stringDoubleEntry -> stringDoubleEntry.setValue(stringDoubleEntry.getValue() * 2)); //multiply values which are not null


                                In case you need a second map where just values in which are not null just use the forEach to put them into your new map.






                                share|improve this answer












                                It can be done like that



                                someMap.entrySet().stream()
                                .filter(stringDoubleEntry -> stringDoubleEntry.getValue() != null) //filter null values out
                                .forEach(stringDoubleEntry -> stringDoubleEntry.setValue(stringDoubleEntry.getValue() * 2)); //multiply values which are not null


                                In case you need a second map where just values in which are not null just use the forEach to put them into your new map.







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered 31 mins ago









                                CodeMatrix

                                8251519




                                8251519







                                • 1




                                  This solution does what the OP's code does in a nice form (though stringDoubleEntry is a bit unaccustomedly long). It exploits that the entries are backed by the map; no new map is created.
                                  – Joop Eggen
                                  17 mins ago






                                • 1




                                  I did not want to criticize, indeed the other way around. There was no upvote and others were already upvoted, despite your solution being straight-forward efficient.
                                  – Joop Eggen
                                  12 mins ago










                                • My mistake I read over 2 words which were the key that was different haha.
                                  – CodeMatrix
                                  10 mins ago













                                • 1




                                  This solution does what the OP's code does in a nice form (though stringDoubleEntry is a bit unaccustomedly long). It exploits that the entries are backed by the map; no new map is created.
                                  – Joop Eggen
                                  17 mins ago






                                • 1




                                  I did not want to criticize, indeed the other way around. There was no upvote and others were already upvoted, despite your solution being straight-forward efficient.
                                  – Joop Eggen
                                  12 mins ago










                                • My mistake I read over 2 words which were the key that was different haha.
                                  – CodeMatrix
                                  10 mins ago








                                1




                                1




                                This solution does what the OP's code does in a nice form (though stringDoubleEntry is a bit unaccustomedly long). It exploits that the entries are backed by the map; no new map is created.
                                – Joop Eggen
                                17 mins ago




                                This solution does what the OP's code does in a nice form (though stringDoubleEntry is a bit unaccustomedly long). It exploits that the entries are backed by the map; no new map is created.
                                – Joop Eggen
                                17 mins ago




                                1




                                1




                                I did not want to criticize, indeed the other way around. There was no upvote and others were already upvoted, despite your solution being straight-forward efficient.
                                – Joop Eggen
                                12 mins ago




                                I did not want to criticize, indeed the other way around. There was no upvote and others were already upvoted, despite your solution being straight-forward efficient.
                                – Joop Eggen
                                12 mins ago












                                My mistake I read over 2 words which were the key that was different haha.
                                – CodeMatrix
                                10 mins ago





                                My mistake I read over 2 words which were the key that was different haha.
                                – CodeMatrix
                                10 mins ago











                                up vote
                                2
                                down vote













                                You can achieve that by converting into a stream, something like:



                                 someMap.entrySet()
                                .forEach(entry ->
                                if(entry.getValue() != null)
                                adjustedMap.put(entry.getKey(), someMap.get(entry.getKey()) * 2);
                                else
                                adjustedMap.put(entry.getKey(), null);

                                );


                                which can be shorted to :



                                someMap.forEach((key, value) -> 
                                if (value != null)
                                adjustedMap.put(key, value * 2);
                                else
                                adjustedMap.put(key, null);

                                );


                                So, if you'r having a map with:



                                Map<String, Double> someMap = new HashMap<>();
                                someMap.put("test1", 1d);
                                someMap.put("test2", 2d);
                                someMap.put("test3", 3d);
                                someMap.put("testNull", null);
                                someMap.put("test4", 4d);


                                You will get this output:




                                test4=8.0, test2=4.0, test3=6.0, testNull=null, test1=2.0







                                share|improve this answer


















                                • 3




                                  The OP wanted to "keep the nulls as nulls.", not filter them out.
                                  – Eran
                                  22 mins ago










                                • @Eran My bad, i'm fixing, thanks
                                  – Leviand
                                  21 mins ago











                                • @Eran fixed, thanks for pointing it
                                  – Leviand
                                  9 mins ago










                                • Your someMap.get(key) can be simply value instead. Anyway, downvoting for style. It may be my personal subjective preference, but I strongly believe functional code should be side-effect free. Therefore, using forEach() on one map to change a different map is a no-no in my book. I'd prefer collecting the stream into a new map instead. That's the canonical and recognized way of consuming streams.
                                  – Petr Janeček
                                  3 mins ago














                                up vote
                                2
                                down vote













                                You can achieve that by converting into a stream, something like:



                                 someMap.entrySet()
                                .forEach(entry ->
                                if(entry.getValue() != null)
                                adjustedMap.put(entry.getKey(), someMap.get(entry.getKey()) * 2);
                                else
                                adjustedMap.put(entry.getKey(), null);

                                );


                                which can be shorted to :



                                someMap.forEach((key, value) -> 
                                if (value != null)
                                adjustedMap.put(key, value * 2);
                                else
                                adjustedMap.put(key, null);

                                );


                                So, if you'r having a map with:



                                Map<String, Double> someMap = new HashMap<>();
                                someMap.put("test1", 1d);
                                someMap.put("test2", 2d);
                                someMap.put("test3", 3d);
                                someMap.put("testNull", null);
                                someMap.put("test4", 4d);


                                You will get this output:




                                test4=8.0, test2=4.0, test3=6.0, testNull=null, test1=2.0







                                share|improve this answer


















                                • 3




                                  The OP wanted to "keep the nulls as nulls.", not filter them out.
                                  – Eran
                                  22 mins ago










                                • @Eran My bad, i'm fixing, thanks
                                  – Leviand
                                  21 mins ago











                                • @Eran fixed, thanks for pointing it
                                  – Leviand
                                  9 mins ago










                                • Your someMap.get(key) can be simply value instead. Anyway, downvoting for style. It may be my personal subjective preference, but I strongly believe functional code should be side-effect free. Therefore, using forEach() on one map to change a different map is a no-no in my book. I'd prefer collecting the stream into a new map instead. That's the canonical and recognized way of consuming streams.
                                  – Petr Janeček
                                  3 mins ago












                                up vote
                                2
                                down vote










                                up vote
                                2
                                down vote









                                You can achieve that by converting into a stream, something like:



                                 someMap.entrySet()
                                .forEach(entry ->
                                if(entry.getValue() != null)
                                adjustedMap.put(entry.getKey(), someMap.get(entry.getKey()) * 2);
                                else
                                adjustedMap.put(entry.getKey(), null);

                                );


                                which can be shorted to :



                                someMap.forEach((key, value) -> 
                                if (value != null)
                                adjustedMap.put(key, value * 2);
                                else
                                adjustedMap.put(key, null);

                                );


                                So, if you'r having a map with:



                                Map<String, Double> someMap = new HashMap<>();
                                someMap.put("test1", 1d);
                                someMap.put("test2", 2d);
                                someMap.put("test3", 3d);
                                someMap.put("testNull", null);
                                someMap.put("test4", 4d);


                                You will get this output:




                                test4=8.0, test2=4.0, test3=6.0, testNull=null, test1=2.0







                                share|improve this answer














                                You can achieve that by converting into a stream, something like:



                                 someMap.entrySet()
                                .forEach(entry ->
                                if(entry.getValue() != null)
                                adjustedMap.put(entry.getKey(), someMap.get(entry.getKey()) * 2);
                                else
                                adjustedMap.put(entry.getKey(), null);

                                );


                                which can be shorted to :



                                someMap.forEach((key, value) -> 
                                if (value != null)
                                adjustedMap.put(key, value * 2);
                                else
                                adjustedMap.put(key, null);

                                );


                                So, if you'r having a map with:



                                Map<String, Double> someMap = new HashMap<>();
                                someMap.put("test1", 1d);
                                someMap.put("test2", 2d);
                                someMap.put("test3", 3d);
                                someMap.put("testNull", null);
                                someMap.put("test4", 4d);


                                You will get this output:




                                test4=8.0, test2=4.0, test3=6.0, testNull=null, test1=2.0








                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited 2 mins ago

























                                answered 34 mins ago









                                Leviand

                                1,3881122




                                1,3881122







                                • 3




                                  The OP wanted to "keep the nulls as nulls.", not filter them out.
                                  – Eran
                                  22 mins ago










                                • @Eran My bad, i'm fixing, thanks
                                  – Leviand
                                  21 mins ago











                                • @Eran fixed, thanks for pointing it
                                  – Leviand
                                  9 mins ago










                                • Your someMap.get(key) can be simply value instead. Anyway, downvoting for style. It may be my personal subjective preference, but I strongly believe functional code should be side-effect free. Therefore, using forEach() on one map to change a different map is a no-no in my book. I'd prefer collecting the stream into a new map instead. That's the canonical and recognized way of consuming streams.
                                  – Petr Janeček
                                  3 mins ago












                                • 3




                                  The OP wanted to "keep the nulls as nulls.", not filter them out.
                                  – Eran
                                  22 mins ago










                                • @Eran My bad, i'm fixing, thanks
                                  – Leviand
                                  21 mins ago











                                • @Eran fixed, thanks for pointing it
                                  – Leviand
                                  9 mins ago










                                • Your someMap.get(key) can be simply value instead. Anyway, downvoting for style. It may be my personal subjective preference, but I strongly believe functional code should be side-effect free. Therefore, using forEach() on one map to change a different map is a no-no in my book. I'd prefer collecting the stream into a new map instead. That's the canonical and recognized way of consuming streams.
                                  – Petr Janeček
                                  3 mins ago







                                3




                                3




                                The OP wanted to "keep the nulls as nulls.", not filter them out.
                                – Eran
                                22 mins ago




                                The OP wanted to "keep the nulls as nulls.", not filter them out.
                                – Eran
                                22 mins ago












                                @Eran My bad, i'm fixing, thanks
                                – Leviand
                                21 mins ago





                                @Eran My bad, i'm fixing, thanks
                                – Leviand
                                21 mins ago













                                @Eran fixed, thanks for pointing it
                                – Leviand
                                9 mins ago




                                @Eran fixed, thanks for pointing it
                                – Leviand
                                9 mins ago












                                Your someMap.get(key) can be simply value instead. Anyway, downvoting for style. It may be my personal subjective preference, but I strongly believe functional code should be side-effect free. Therefore, using forEach() on one map to change a different map is a no-no in my book. I'd prefer collecting the stream into a new map instead. That's the canonical and recognized way of consuming streams.
                                – Petr Janeček
                                3 mins ago




                                Your someMap.get(key) can be simply value instead. Anyway, downvoting for style. It may be my personal subjective preference, but I strongly believe functional code should be side-effect free. Therefore, using forEach() on one map to change a different map is a no-no in my book. I'd prefer collecting the stream into a new map instead. That's the canonical and recognized way of consuming streams.
                                – Petr Janeček
                                3 mins ago










                                up vote
                                1
                                down vote













                                Use like this.



                                 Map<String, Double> adjustedMap = map.entrySet().stream()filter(x -> x.getValue() != null)
                                .collect(Collectors.toMap(x -> x.getKey(), x -> 2*x.getValue()));
                                //printing
                                adjustedMap.entrySet().stream().forEach(System.out::println);





                                share|improve this answer






















                                • This is not null safe
                                  – Eran
                                  26 mins ago














                                up vote
                                1
                                down vote













                                Use like this.



                                 Map<String, Double> adjustedMap = map.entrySet().stream()filter(x -> x.getValue() != null)
                                .collect(Collectors.toMap(x -> x.getKey(), x -> 2*x.getValue()));
                                //printing
                                adjustedMap.entrySet().stream().forEach(System.out::println);





                                share|improve this answer






















                                • This is not null safe
                                  – Eran
                                  26 mins ago












                                up vote
                                1
                                down vote










                                up vote
                                1
                                down vote









                                Use like this.



                                 Map<String, Double> adjustedMap = map.entrySet().stream()filter(x -> x.getValue() != null)
                                .collect(Collectors.toMap(x -> x.getKey(), x -> 2*x.getValue()));
                                //printing
                                adjustedMap.entrySet().stream().forEach(System.out::println);





                                share|improve this answer














                                Use like this.



                                 Map<String, Double> adjustedMap = map.entrySet().stream()filter(x -> x.getValue() != null)
                                .collect(Collectors.toMap(x -> x.getKey(), x -> 2*x.getValue()));
                                //printing
                                adjustedMap.entrySet().stream().forEach(System.out::println);






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited 23 mins ago

























                                answered 30 mins ago









                                amitpandey

                                158111




                                158111











                                • This is not null safe
                                  – Eran
                                  26 mins ago
















                                • This is not null safe
                                  – Eran
                                  26 mins ago















                                This is not null safe
                                – Eran
                                26 mins ago




                                This is not null safe
                                – Eran
                                26 mins ago










                                up vote
                                1
                                down vote













                                You can do this with this code:



                                 Map<String, Double> map = new HashMap<>();
                                map.put("1", 3.0);
                                map.put("3", null);
                                map.put("2", 5.0);

                                Map<String, Double> res = map.entrySet().stream()
                                .collect(HashMap::new, (m,v)->m.put(v.getKey(), v.getValue() != null ? v.getValue() * 2 : null), HashMap::putAll);

                                System.out.println(res);


                                and the output will be:




                                1=6.0, 2=10.0, 3=null




                                It will allow you to keep null values in the map.






                                share|improve this answer


























                                  up vote
                                  1
                                  down vote













                                  You can do this with this code:



                                   Map<String, Double> map = new HashMap<>();
                                  map.put("1", 3.0);
                                  map.put("3", null);
                                  map.put("2", 5.0);

                                  Map<String, Double> res = map.entrySet().stream()
                                  .collect(HashMap::new, (m,v)->m.put(v.getKey(), v.getValue() != null ? v.getValue() * 2 : null), HashMap::putAll);

                                  System.out.println(res);


                                  and the output will be:




                                  1=6.0, 2=10.0, 3=null




                                  It will allow you to keep null values in the map.






                                  share|improve this answer
























                                    up vote
                                    1
                                    down vote










                                    up vote
                                    1
                                    down vote









                                    You can do this with this code:



                                     Map<String, Double> map = new HashMap<>();
                                    map.put("1", 3.0);
                                    map.put("3", null);
                                    map.put("2", 5.0);

                                    Map<String, Double> res = map.entrySet().stream()
                                    .collect(HashMap::new, (m,v)->m.put(v.getKey(), v.getValue() != null ? v.getValue() * 2 : null), HashMap::putAll);

                                    System.out.println(res);


                                    and the output will be:




                                    1=6.0, 2=10.0, 3=null




                                    It will allow you to keep null values in the map.






                                    share|improve this answer














                                    You can do this with this code:



                                     Map<String, Double> map = new HashMap<>();
                                    map.put("1", 3.0);
                                    map.put("3", null);
                                    map.put("2", 5.0);

                                    Map<String, Double> res = map.entrySet().stream()
                                    .collect(HashMap::new, (m,v)->m.put(v.getKey(), v.getValue() != null ? v.getValue() * 2 : null), HashMap::putAll);

                                    System.out.println(res);


                                    and the output will be:




                                    1=6.0, 2=10.0, 3=null




                                    It will allow you to keep null values in the map.







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited 18 mins ago

























                                    answered 24 mins ago









                                    user987339

                                    7,86862936




                                    7,86862936




















                                        up vote
                                        1
                                        down vote













                                        To keep null values you can use something as simple as :



                                        someMap.keySet()
                                        .stream()
                                        .forEach(key -> adjustedMap.put(key, (someMap.get(key)) == null ? null : someMap.get(key) * 2));





                                        share|improve this answer




















                                        • You should absolutely stream on the entrySet(), they you'd avoid calling someMap.get(key) in a loop, and would be able to just do entry.value() instead. Anyway, downvoting for style. It may be my personal subjective preference, but I strongly believe functional code should be side-effect free. Therefore, using forEach() on one map to change a different map is a no-no in my book. I'd prefer collecting the stream into a new map instead. That's the canonical and recognized way of consuming streams.
                                          – Petr Janeček
                                          5 mins ago














                                        up vote
                                        1
                                        down vote













                                        To keep null values you can use something as simple as :



                                        someMap.keySet()
                                        .stream()
                                        .forEach(key -> adjustedMap.put(key, (someMap.get(key)) == null ? null : someMap.get(key) * 2));





                                        share|improve this answer




















                                        • You should absolutely stream on the entrySet(), they you'd avoid calling someMap.get(key) in a loop, and would be able to just do entry.value() instead. Anyway, downvoting for style. It may be my personal subjective preference, but I strongly believe functional code should be side-effect free. Therefore, using forEach() on one map to change a different map is a no-no in my book. I'd prefer collecting the stream into a new map instead. That's the canonical and recognized way of consuming streams.
                                          – Petr Janeček
                                          5 mins ago












                                        up vote
                                        1
                                        down vote










                                        up vote
                                        1
                                        down vote









                                        To keep null values you can use something as simple as :



                                        someMap.keySet()
                                        .stream()
                                        .forEach(key -> adjustedMap.put(key, (someMap.get(key)) == null ? null : someMap.get(key) * 2));





                                        share|improve this answer












                                        To keep null values you can use something as simple as :



                                        someMap.keySet()
                                        .stream()
                                        .forEach(key -> adjustedMap.put(key, (someMap.get(key)) == null ? null : someMap.get(key) * 2));






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered 18 mins ago









                                        c0der

                                        7,31241643




                                        7,31241643











                                        • You should absolutely stream on the entrySet(), they you'd avoid calling someMap.get(key) in a loop, and would be able to just do entry.value() instead. Anyway, downvoting for style. It may be my personal subjective preference, but I strongly believe functional code should be side-effect free. Therefore, using forEach() on one map to change a different map is a no-no in my book. I'd prefer collecting the stream into a new map instead. That's the canonical and recognized way of consuming streams.
                                          – Petr Janeček
                                          5 mins ago
















                                        • You should absolutely stream on the entrySet(), they you'd avoid calling someMap.get(key) in a loop, and would be able to just do entry.value() instead. Anyway, downvoting for style. It may be my personal subjective preference, but I strongly believe functional code should be side-effect free. Therefore, using forEach() on one map to change a different map is a no-no in my book. I'd prefer collecting the stream into a new map instead. That's the canonical and recognized way of consuming streams.
                                          – Petr Janeček
                                          5 mins ago















                                        You should absolutely stream on the entrySet(), they you'd avoid calling someMap.get(key) in a loop, and would be able to just do entry.value() instead. Anyway, downvoting for style. It may be my personal subjective preference, but I strongly believe functional code should be side-effect free. Therefore, using forEach() on one map to change a different map is a no-no in my book. I'd prefer collecting the stream into a new map instead. That's the canonical and recognized way of consuming streams.
                                        – Petr Janeček
                                        5 mins ago




                                        You should absolutely stream on the entrySet(), they you'd avoid calling someMap.get(key) in a loop, and would be able to just do entry.value() instead. Anyway, downvoting for style. It may be my personal subjective preference, but I strongly believe functional code should be side-effect free. Therefore, using forEach() on one map to change a different map is a no-no in my book. I'd prefer collecting the stream into a new map instead. That's the canonical and recognized way of consuming streams.
                                        – Petr Janeček
                                        5 mins ago










                                        up vote
                                        1
                                        down vote













                                        Try something like this with java 8 steam api



                                        Map<String, Double> newMap = oldMap.entrySet().stream()
                                        .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue() == null ? null: x.getValue()*2));





                                        share|improve this answer






















                                        • This will throw NullPointerException for any null values.
                                          – Eran
                                          24 mins ago










                                        • how is it possible ?
                                          – oguzhan aygun
                                          22 mins ago







                                        • 3




                                          That's the behavior of Collectors.toMap. You can try it and see for yourself.
                                          – Eran
                                          20 mins ago










                                        • thank you Eran I just tried and learn something new :)
                                          – oguzhan aygun
                                          14 mins ago














                                        up vote
                                        1
                                        down vote













                                        Try something like this with java 8 steam api



                                        Map<String, Double> newMap = oldMap.entrySet().stream()
                                        .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue() == null ? null: x.getValue()*2));





                                        share|improve this answer






















                                        • This will throw NullPointerException for any null values.
                                          – Eran
                                          24 mins ago










                                        • how is it possible ?
                                          – oguzhan aygun
                                          22 mins ago







                                        • 3




                                          That's the behavior of Collectors.toMap. You can try it and see for yourself.
                                          – Eran
                                          20 mins ago










                                        • thank you Eran I just tried and learn something new :)
                                          – oguzhan aygun
                                          14 mins ago












                                        up vote
                                        1
                                        down vote










                                        up vote
                                        1
                                        down vote









                                        Try something like this with java 8 steam api



                                        Map<String, Double> newMap = oldMap.entrySet().stream()
                                        .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue() == null ? null: x.getValue()*2));





                                        share|improve this answer














                                        Try something like this with java 8 steam api



                                        Map<String, Double> newMap = oldMap.entrySet().stream()
                                        .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue() == null ? null: x.getValue()*2));






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited 14 mins ago









                                        Nicholas K

                                        2,6502725




                                        2,6502725










                                        answered 27 mins ago









                                        oguzhan aygun

                                        3018




                                        3018











                                        • This will throw NullPointerException for any null values.
                                          – Eran
                                          24 mins ago










                                        • how is it possible ?
                                          – oguzhan aygun
                                          22 mins ago







                                        • 3




                                          That's the behavior of Collectors.toMap. You can try it and see for yourself.
                                          – Eran
                                          20 mins ago










                                        • thank you Eran I just tried and learn something new :)
                                          – oguzhan aygun
                                          14 mins ago
















                                        • This will throw NullPointerException for any null values.
                                          – Eran
                                          24 mins ago










                                        • how is it possible ?
                                          – oguzhan aygun
                                          22 mins ago







                                        • 3




                                          That's the behavior of Collectors.toMap. You can try it and see for yourself.
                                          – Eran
                                          20 mins ago










                                        • thank you Eran I just tried and learn something new :)
                                          – oguzhan aygun
                                          14 mins ago















                                        This will throw NullPointerException for any null values.
                                        – Eran
                                        24 mins ago




                                        This will throw NullPointerException for any null values.
                                        – Eran
                                        24 mins ago












                                        how is it possible ?
                                        – oguzhan aygun
                                        22 mins ago





                                        how is it possible ?
                                        – oguzhan aygun
                                        22 mins ago





                                        3




                                        3




                                        That's the behavior of Collectors.toMap. You can try it and see for yourself.
                                        – Eran
                                        20 mins ago




                                        That's the behavior of Collectors.toMap. You can try it and see for yourself.
                                        – Eran
                                        20 mins ago












                                        thank you Eran I just tried and learn something new :)
                                        – oguzhan aygun
                                        14 mins ago




                                        thank you Eran I just tried and learn something new :)
                                        – oguzhan aygun
                                        14 mins ago

















                                         

                                        draft saved


                                        draft discarded















































                                         


                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function ()
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52850108%2fis-there-a-clean-and-null-safe-way-to-multiply-the-values-of-a-map-in-java%23new-answer', 'question_page');

                                        );

                                        Post as a guest













































































                                        Comments

                                        Popular posts from this blog

                                        What does second last employer means? [closed]

                                        List of Gilmore Girls characters

                                        Confectionery