Java 8 streams - merge a collection of Maps2019 Community Moderator ElectionIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?A Java collection of value pairs? (tuples?)How do I convert a String to an int in Java?Creating a memory leak with JavaJava 8 List<V> into Map<K, V>How to Convert a Java 8 Stream to an Array?
Is this Pascal's Matrix?
Turning a hard to access nut?
What will the Frenchman say?
Homology of the fiber
Recursively updating the MLE as new observations stream in
How old is Nick Fury?
What are the rules for concealing thieves' tools (or items in general)?
Have any astronauts/cosmonauts died in space?
Why is indicated airspeed rather than ground speed used during the takeoff roll?
Why are there no stars visible in cislunar space?
Fair way to split coins
Error in master's thesis, I do not know what to do
What (if any) is the reason to buy in small local stores?
If I cast the Enlarge/Reduce spell on an arrow, what weapon could it count as?
Are hand made posters acceptable in Academia?
Why is this tree refusing to shed its dead leaves?
Animating wave motion in water
Can "few" be used as a subject? If so, what is the rule?
pipe commands inside find -exec?
Why I don't get the wanted width of tcbox?
Why is participating in the European Parliamentary elections used as a threat?
What is the reasoning behind standardization (dividing by standard deviation)?
Do I need to convey a moral for each of my blog post?
Do people actually use the word "kaputt" in conversation?
Java 8 streams - merge a collection of Maps
2019 Community Moderator ElectionIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?A Java collection of value pairs? (tuples?)How do I convert a String to an int in Java?Creating a memory leak with JavaJava 8 List<V> into Map<K, V>How to Convert a Java 8 Stream to an Array?
Lets say I have a method with a following signature:
Map<String, String> merge (String[][] ... maps)
It takes a (variadic) number of two-dim arrays which represent mappings, for example:
String[][] m1 = new String[][]
"k1", "a",
"k2", "b"
;
String[][] m2 = new String[][]
"k1", "a",
"k2", "b",
"k3", "c"
;
String[][] m3 = new String[][]
"k1", "x",
"k2", "b"
;
Now I can merge any two of the maps left-to-right like this:
Map<String, String> m1 = Stream.of(map1).collect(Collectors.toMap(k -> k[0], v -> v[1]));
Map<String, String> m2 = Stream.of(map2).collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null")));
m1.forEach((key, value) -> m2.merge(key, value, (v1, v2) -> v1));
But how can I go about merging a variadic number of such array-maps, so that after passing m1, m2, m3
as defined above the result is:
String[][] m3 = new String[][]
"k1", "x",
"k2", "b"
"k3", "c"
;
java java-8 java-stream
add a comment |
Lets say I have a method with a following signature:
Map<String, String> merge (String[][] ... maps)
It takes a (variadic) number of two-dim arrays which represent mappings, for example:
String[][] m1 = new String[][]
"k1", "a",
"k2", "b"
;
String[][] m2 = new String[][]
"k1", "a",
"k2", "b",
"k3", "c"
;
String[][] m3 = new String[][]
"k1", "x",
"k2", "b"
;
Now I can merge any two of the maps left-to-right like this:
Map<String, String> m1 = Stream.of(map1).collect(Collectors.toMap(k -> k[0], v -> v[1]));
Map<String, String> m2 = Stream.of(map2).collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null")));
m1.forEach((key, value) -> m2.merge(key, value, (v1, v2) -> v1));
But how can I go about merging a variadic number of such array-maps, so that after passing m1, m2, m3
as defined above the result is:
String[][] m3 = new String[][]
"k1", "x",
"k2", "b"
"k3", "c"
;
java java-8 java-stream
add a comment |
Lets say I have a method with a following signature:
Map<String, String> merge (String[][] ... maps)
It takes a (variadic) number of two-dim arrays which represent mappings, for example:
String[][] m1 = new String[][]
"k1", "a",
"k2", "b"
;
String[][] m2 = new String[][]
"k1", "a",
"k2", "b",
"k3", "c"
;
String[][] m3 = new String[][]
"k1", "x",
"k2", "b"
;
Now I can merge any two of the maps left-to-right like this:
Map<String, String> m1 = Stream.of(map1).collect(Collectors.toMap(k -> k[0], v -> v[1]));
Map<String, String> m2 = Stream.of(map2).collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null")));
m1.forEach((key, value) -> m2.merge(key, value, (v1, v2) -> v1));
But how can I go about merging a variadic number of such array-maps, so that after passing m1, m2, m3
as defined above the result is:
String[][] m3 = new String[][]
"k1", "x",
"k2", "b"
"k3", "c"
;
java java-8 java-stream
Lets say I have a method with a following signature:
Map<String, String> merge (String[][] ... maps)
It takes a (variadic) number of two-dim arrays which represent mappings, for example:
String[][] m1 = new String[][]
"k1", "a",
"k2", "b"
;
String[][] m2 = new String[][]
"k1", "a",
"k2", "b",
"k3", "c"
;
String[][] m3 = new String[][]
"k1", "x",
"k2", "b"
;
Now I can merge any two of the maps left-to-right like this:
Map<String, String> m1 = Stream.of(map1).collect(Collectors.toMap(k -> k[0], v -> v[1]));
Map<String, String> m2 = Stream.of(map2).collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null")));
m1.forEach((key, value) -> m2.merge(key, value, (v1, v2) -> v1));
But how can I go about merging a variadic number of such array-maps, so that after passing m1, m2, m3
as defined above the result is:
String[][] m3 = new String[][]
"k1", "x",
"k2", "b"
"k3", "c"
;
java java-8 java-stream
java java-8 java-stream
asked Mar 6 at 23:22
fbielejecfbielejec
1,23531630
1,23531630
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
It's quite simple, if I'm understanding your question correctly. You just flatMap all the entries and collect to map, with a merge function that selects the later value:
Map<String, String> merge (String[][] ... maps)
return Arrays.stream(maps)
.flatMap(Arrays::stream)
.collect(Collectors.toMap(a -> a[0], a -> a[1], (a, b) -> b));
If you want to convert it back to an array, you can do
String[][] m3 = merge(maps)
.entrySet()
.stream()
.map(e -> new String[] e.getKey(), e.getValue() )
.toArray(String[][]::new);
Quite nice, I just added some null punning, for safetyreturn Arrays.stream(maps) .flatMap(Arrays::stream) .collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null"), (v1, v2) -> v2));
– fbielejec
Mar 7 at 9:35
2
@fbielejec instead ofOptional.ofNullable(v[1]).orElse("null")
you can simply useString.valueOf(v[1])
. Evenv[1] == null? "null": v[1]
is simpler…
– Holger
Mar 7 at 13:40
Yes indeed, thank you. Bit of context: these are then passed to logging and used as meta information (serialized to JSON) This can throw npe in some edge cases, hence the extra protection.
– fbielejec
Mar 7 at 17:55
add a comment |
Map<String, String> merge(String[][]... maps)
return Stream.of(maps)
.flatMap(Arrays::stream) //flatten all maps into a single stream
.map(s -> Map.entry(s[0], s[1])) //convert array to Entry
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(o1, o2) -> o2));
Edit: No need to convert to Entry. We can directly collect to map as @shmosel showed.
2
Worth noting that Map.entry exists from Java 9 onwards
– LppEdd
Mar 6 at 23:36
1
@LppEdd and doesn’t supportnull
values. Which seems to be an issue for the OP.
– Holger
Mar 7 at 13:42
@HolgerSimpleEntry
to the rescue. Although it's not needed at all as Kartik pointed out.
– LppEdd
Mar 7 at 14:22
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
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
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55033758%2fjava-8-streams-merge-a-collection-of-maps%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
It's quite simple, if I'm understanding your question correctly. You just flatMap all the entries and collect to map, with a merge function that selects the later value:
Map<String, String> merge (String[][] ... maps)
return Arrays.stream(maps)
.flatMap(Arrays::stream)
.collect(Collectors.toMap(a -> a[0], a -> a[1], (a, b) -> b));
If you want to convert it back to an array, you can do
String[][] m3 = merge(maps)
.entrySet()
.stream()
.map(e -> new String[] e.getKey(), e.getValue() )
.toArray(String[][]::new);
Quite nice, I just added some null punning, for safetyreturn Arrays.stream(maps) .flatMap(Arrays::stream) .collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null"), (v1, v2) -> v2));
– fbielejec
Mar 7 at 9:35
2
@fbielejec instead ofOptional.ofNullable(v[1]).orElse("null")
you can simply useString.valueOf(v[1])
. Evenv[1] == null? "null": v[1]
is simpler…
– Holger
Mar 7 at 13:40
Yes indeed, thank you. Bit of context: these are then passed to logging and used as meta information (serialized to JSON) This can throw npe in some edge cases, hence the extra protection.
– fbielejec
Mar 7 at 17:55
add a comment |
It's quite simple, if I'm understanding your question correctly. You just flatMap all the entries and collect to map, with a merge function that selects the later value:
Map<String, String> merge (String[][] ... maps)
return Arrays.stream(maps)
.flatMap(Arrays::stream)
.collect(Collectors.toMap(a -> a[0], a -> a[1], (a, b) -> b));
If you want to convert it back to an array, you can do
String[][] m3 = merge(maps)
.entrySet()
.stream()
.map(e -> new String[] e.getKey(), e.getValue() )
.toArray(String[][]::new);
Quite nice, I just added some null punning, for safetyreturn Arrays.stream(maps) .flatMap(Arrays::stream) .collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null"), (v1, v2) -> v2));
– fbielejec
Mar 7 at 9:35
2
@fbielejec instead ofOptional.ofNullable(v[1]).orElse("null")
you can simply useString.valueOf(v[1])
. Evenv[1] == null? "null": v[1]
is simpler…
– Holger
Mar 7 at 13:40
Yes indeed, thank you. Bit of context: these are then passed to logging and used as meta information (serialized to JSON) This can throw npe in some edge cases, hence the extra protection.
– fbielejec
Mar 7 at 17:55
add a comment |
It's quite simple, if I'm understanding your question correctly. You just flatMap all the entries and collect to map, with a merge function that selects the later value:
Map<String, String> merge (String[][] ... maps)
return Arrays.stream(maps)
.flatMap(Arrays::stream)
.collect(Collectors.toMap(a -> a[0], a -> a[1], (a, b) -> b));
If you want to convert it back to an array, you can do
String[][] m3 = merge(maps)
.entrySet()
.stream()
.map(e -> new String[] e.getKey(), e.getValue() )
.toArray(String[][]::new);
It's quite simple, if I'm understanding your question correctly. You just flatMap all the entries and collect to map, with a merge function that selects the later value:
Map<String, String> merge (String[][] ... maps)
return Arrays.stream(maps)
.flatMap(Arrays::stream)
.collect(Collectors.toMap(a -> a[0], a -> a[1], (a, b) -> b));
If you want to convert it back to an array, you can do
String[][] m3 = merge(maps)
.entrySet()
.stream()
.map(e -> new String[] e.getKey(), e.getValue() )
.toArray(String[][]::new);
edited Mar 6 at 23:54
answered Mar 6 at 23:38
shmoselshmosel
36.8k43996
36.8k43996
Quite nice, I just added some null punning, for safetyreturn Arrays.stream(maps) .flatMap(Arrays::stream) .collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null"), (v1, v2) -> v2));
– fbielejec
Mar 7 at 9:35
2
@fbielejec instead ofOptional.ofNullable(v[1]).orElse("null")
you can simply useString.valueOf(v[1])
. Evenv[1] == null? "null": v[1]
is simpler…
– Holger
Mar 7 at 13:40
Yes indeed, thank you. Bit of context: these are then passed to logging and used as meta information (serialized to JSON) This can throw npe in some edge cases, hence the extra protection.
– fbielejec
Mar 7 at 17:55
add a comment |
Quite nice, I just added some null punning, for safetyreturn Arrays.stream(maps) .flatMap(Arrays::stream) .collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null"), (v1, v2) -> v2));
– fbielejec
Mar 7 at 9:35
2
@fbielejec instead ofOptional.ofNullable(v[1]).orElse("null")
you can simply useString.valueOf(v[1])
. Evenv[1] == null? "null": v[1]
is simpler…
– Holger
Mar 7 at 13:40
Yes indeed, thank you. Bit of context: these are then passed to logging and used as meta information (serialized to JSON) This can throw npe in some edge cases, hence the extra protection.
– fbielejec
Mar 7 at 17:55
Quite nice, I just added some null punning, for safety
return Arrays.stream(maps) .flatMap(Arrays::stream) .collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null"), (v1, v2) -> v2));
– fbielejec
Mar 7 at 9:35
Quite nice, I just added some null punning, for safety
return Arrays.stream(maps) .flatMap(Arrays::stream) .collect(Collectors.toMap(k -> k[0], v -> Optional.ofNullable(v[1]).orElse("null"), (v1, v2) -> v2));
– fbielejec
Mar 7 at 9:35
2
2
@fbielejec instead of
Optional.ofNullable(v[1]).orElse("null")
you can simply use String.valueOf(v[1])
. Even v[1] == null? "null": v[1]
is simpler…– Holger
Mar 7 at 13:40
@fbielejec instead of
Optional.ofNullable(v[1]).orElse("null")
you can simply use String.valueOf(v[1])
. Even v[1] == null? "null": v[1]
is simpler…– Holger
Mar 7 at 13:40
Yes indeed, thank you. Bit of context: these are then passed to logging and used as meta information (serialized to JSON) This can throw npe in some edge cases, hence the extra protection.
– fbielejec
Mar 7 at 17:55
Yes indeed, thank you. Bit of context: these are then passed to logging and used as meta information (serialized to JSON) This can throw npe in some edge cases, hence the extra protection.
– fbielejec
Mar 7 at 17:55
add a comment |
Map<String, String> merge(String[][]... maps)
return Stream.of(maps)
.flatMap(Arrays::stream) //flatten all maps into a single stream
.map(s -> Map.entry(s[0], s[1])) //convert array to Entry
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(o1, o2) -> o2));
Edit: No need to convert to Entry. We can directly collect to map as @shmosel showed.
2
Worth noting that Map.entry exists from Java 9 onwards
– LppEdd
Mar 6 at 23:36
1
@LppEdd and doesn’t supportnull
values. Which seems to be an issue for the OP.
– Holger
Mar 7 at 13:42
@HolgerSimpleEntry
to the rescue. Although it's not needed at all as Kartik pointed out.
– LppEdd
Mar 7 at 14:22
add a comment |
Map<String, String> merge(String[][]... maps)
return Stream.of(maps)
.flatMap(Arrays::stream) //flatten all maps into a single stream
.map(s -> Map.entry(s[0], s[1])) //convert array to Entry
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(o1, o2) -> o2));
Edit: No need to convert to Entry. We can directly collect to map as @shmosel showed.
2
Worth noting that Map.entry exists from Java 9 onwards
– LppEdd
Mar 6 at 23:36
1
@LppEdd and doesn’t supportnull
values. Which seems to be an issue for the OP.
– Holger
Mar 7 at 13:42
@HolgerSimpleEntry
to the rescue. Although it's not needed at all as Kartik pointed out.
– LppEdd
Mar 7 at 14:22
add a comment |
Map<String, String> merge(String[][]... maps)
return Stream.of(maps)
.flatMap(Arrays::stream) //flatten all maps into a single stream
.map(s -> Map.entry(s[0], s[1])) //convert array to Entry
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(o1, o2) -> o2));
Edit: No need to convert to Entry. We can directly collect to map as @shmosel showed.
Map<String, String> merge(String[][]... maps)
return Stream.of(maps)
.flatMap(Arrays::stream) //flatten all maps into a single stream
.map(s -> Map.entry(s[0], s[1])) //convert array to Entry
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(o1, o2) -> o2));
Edit: No need to convert to Entry. We can directly collect to map as @shmosel showed.
edited Mar 6 at 23:36
answered Mar 6 at 23:34
KartikKartik
4,19731537
4,19731537
2
Worth noting that Map.entry exists from Java 9 onwards
– LppEdd
Mar 6 at 23:36
1
@LppEdd and doesn’t supportnull
values. Which seems to be an issue for the OP.
– Holger
Mar 7 at 13:42
@HolgerSimpleEntry
to the rescue. Although it's not needed at all as Kartik pointed out.
– LppEdd
Mar 7 at 14:22
add a comment |
2
Worth noting that Map.entry exists from Java 9 onwards
– LppEdd
Mar 6 at 23:36
1
@LppEdd and doesn’t supportnull
values. Which seems to be an issue for the OP.
– Holger
Mar 7 at 13:42
@HolgerSimpleEntry
to the rescue. Although it's not needed at all as Kartik pointed out.
– LppEdd
Mar 7 at 14:22
2
2
Worth noting that Map.entry exists from Java 9 onwards
– LppEdd
Mar 6 at 23:36
Worth noting that Map.entry exists from Java 9 onwards
– LppEdd
Mar 6 at 23:36
1
1
@LppEdd and doesn’t support
null
values. Which seems to be an issue for the OP.– Holger
Mar 7 at 13:42
@LppEdd and doesn’t support
null
values. Which seems to be an issue for the OP.– Holger
Mar 7 at 13:42
@Holger
SimpleEntry
to the rescue. Although it's not needed at all as Kartik pointed out.– LppEdd
Mar 7 at 14:22
@Holger
SimpleEntry
to the rescue. Although it's not needed at all as Kartik pointed out.– LppEdd
Mar 7 at 14:22
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
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
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55033758%2fjava-8-streams-merge-a-collection-of-maps%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
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
Required, but never shown
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
Required, but never shown
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
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown