Is there a clean (and null safe) way to multiply the values of a map in Java?
Clash 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
java java-8 java-stream
add a comment |Â
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
java java-8 java-stream
add a comment |Â
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
java java-8 java-stream
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
java java-8 java-stream
edited 27 mins ago
Michael
16.7k63066
16.7k63066
asked 44 mins ago
Omar Haque
1335
1335
add a comment |Â
add a comment |Â
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.
add a comment |Â
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);
add a comment |Â
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.
1
This solution does what the OP's code does in a nice form (thoughstringDoubleEntry
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
add a comment |Â
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
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
YoursomeMap.get(key)
can be simplyvalue
instead. Anyway, downvoting for style. It may be my personal subjective preference, but I strongly believe functional code should be side-effect free. Therefore, usingforEach()
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
add a comment |Â
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);
This is not null safe
– Eran
26 mins ago
add a comment |Â
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.
add a comment |Â
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));
You should absolutely stream on theentrySet()
, they you'd avoid callingsomeMap.get(key)
in a loop, and would be able to just doentry.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, usingforEach()
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
add a comment |Â
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));
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 ofCollectors.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
add a comment |Â
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.
add a comment |Â
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.
add a comment |Â
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.
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.
answered 14 mins ago
Petr JaneÄÂek
28.9k887122
28.9k887122
add a comment |Â
add a comment |Â
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);
add a comment |Â
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);
add a comment |Â
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);
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);
edited 25 mins ago
answered 36 mins ago


Eran
267k34409496
267k34409496
add a comment |Â
add a comment |Â
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.
1
This solution does what the OP's code does in a nice form (thoughstringDoubleEntry
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
add a comment |Â
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.
1
This solution does what the OP's code does in a nice form (thoughstringDoubleEntry
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
add a comment |Â
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.
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.
answered 31 mins ago


CodeMatrix
8251519
8251519
1
This solution does what the OP's code does in a nice form (thoughstringDoubleEntry
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
add a comment |Â
1
This solution does what the OP's code does in a nice form (thoughstringDoubleEntry
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
add a comment |Â
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
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
YoursomeMap.get(key)
can be simplyvalue
instead. Anyway, downvoting for style. It may be my personal subjective preference, but I strongly believe functional code should be side-effect free. Therefore, usingforEach()
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
add a comment |Â
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
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
YoursomeMap.get(key)
can be simplyvalue
instead. Anyway, downvoting for style. It may be my personal subjective preference, but I strongly believe functional code should be side-effect free. Therefore, usingforEach()
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
add a comment |Â
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
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
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
YoursomeMap.get(key)
can be simplyvalue
instead. Anyway, downvoting for style. It may be my personal subjective preference, but I strongly believe functional code should be side-effect free. Therefore, usingforEach()
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
add a comment |Â
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
YoursomeMap.get(key)
can be simplyvalue
instead. Anyway, downvoting for style. It may be my personal subjective preference, but I strongly believe functional code should be side-effect free. Therefore, usingforEach()
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
add a comment |Â
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);
This is not null safe
– Eran
26 mins ago
add a comment |Â
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);
This is not null safe
– Eran
26 mins ago
add a comment |Â
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);
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);
edited 23 mins ago
answered 30 mins ago
amitpandey
158111
158111
This is not null safe
– Eran
26 mins ago
add a comment |Â
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
add a comment |Â
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.
add a comment |Â
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.
add a comment |Â
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.
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.
edited 18 mins ago
answered 24 mins ago


user987339
7,86862936
7,86862936
add a comment |Â
add a comment |Â
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));
You should absolutely stream on theentrySet()
, they you'd avoid callingsomeMap.get(key)
in a loop, and would be able to just doentry.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, usingforEach()
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
add a comment |Â
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));
You should absolutely stream on theentrySet()
, they you'd avoid callingsomeMap.get(key)
in a loop, and would be able to just doentry.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, usingforEach()
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
add a comment |Â
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));
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));
answered 18 mins ago


c0der
7,31241643
7,31241643
You should absolutely stream on theentrySet()
, they you'd avoid callingsomeMap.get(key)
in a loop, and would be able to just doentry.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, usingforEach()
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
add a comment |Â
You should absolutely stream on theentrySet()
, they you'd avoid callingsomeMap.get(key)
in a loop, and would be able to just doentry.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, usingforEach()
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
add a comment |Â
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));
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 ofCollectors.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
add a comment |Â
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));
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 ofCollectors.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
add a comment |Â
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));
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));
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 ofCollectors.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
add a comment |Â
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 ofCollectors.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
add a comment |Â
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password