Convert Map to Map<String, Set> with filter and streams
I would like to convert my map which looks like this:
{
key="someKey1", value=Apple(id="1", color="green"),
key="someKey2", value=Apple(id="2", color="red"),
key="someKey3", value=Apple(id="3", color="green"),
key="someKey4", value=Apple(id="4", color="red"),
}
to another map which puts all apples of the same color into the same list:
{
key="red", value=list={apple1, apple3},
key="green", value=list={apple2, apple4},
}
I tried the following:
Map<String, Set<Apple>> sortedApples = appleMap.entrySet()
.stream()
.collect(Collectors.toMap(l -> l.getColour, ???));
Am I on the right track? Should I use filters for this task? Is there an easier way?
java lambda java-8 java-stream
add a comment |
I would like to convert my map which looks like this:
{
key="someKey1", value=Apple(id="1", color="green"),
key="someKey2", value=Apple(id="2", color="red"),
key="someKey3", value=Apple(id="3", color="green"),
key="someKey4", value=Apple(id="4", color="red"),
}
to another map which puts all apples of the same color into the same list:
{
key="red", value=list={apple1, apple3},
key="green", value=list={apple2, apple4},
}
I tried the following:
Map<String, Set<Apple>> sortedApples = appleMap.entrySet()
.stream()
.collect(Collectors.toMap(l -> l.getColour, ???));
Am I on the right track? Should I use filters for this task? Is there an easier way?
java lambda java-8 java-stream
add a comment |
I would like to convert my map which looks like this:
{
key="someKey1", value=Apple(id="1", color="green"),
key="someKey2", value=Apple(id="2", color="red"),
key="someKey3", value=Apple(id="3", color="green"),
key="someKey4", value=Apple(id="4", color="red"),
}
to another map which puts all apples of the same color into the same list:
{
key="red", value=list={apple1, apple3},
key="green", value=list={apple2, apple4},
}
I tried the following:
Map<String, Set<Apple>> sortedApples = appleMap.entrySet()
.stream()
.collect(Collectors.toMap(l -> l.getColour, ???));
Am I on the right track? Should I use filters for this task? Is there an easier way?
java lambda java-8 java-stream
I would like to convert my map which looks like this:
{
key="someKey1", value=Apple(id="1", color="green"),
key="someKey2", value=Apple(id="2", color="red"),
key="someKey3", value=Apple(id="3", color="green"),
key="someKey4", value=Apple(id="4", color="red"),
}
to another map which puts all apples of the same color into the same list:
{
key="red", value=list={apple1, apple3},
key="green", value=list={apple2, apple4},
}
I tried the following:
Map<String, Set<Apple>> sortedApples = appleMap.entrySet()
.stream()
.collect(Collectors.toMap(l -> l.getColour, ???));
Am I on the right track? Should I use filters for this task? Is there an easier way?
java lambda java-8 java-stream
java lambda java-8 java-stream
edited 10 mins ago
Aomine
39.8k73770
39.8k73770
asked 34 mins ago
M4V3N
528
528
add a comment |
add a comment |
3 Answers
3
active
oldest
votes
Collectors.groupingBy
is more suitable than Collectors.toMap
for this task (though both can be used).
Map<String, List<Apple>> sortedApples =
appleMap.values()
.stream()
.collect(Collectors.groupingBy(Apple::getColour));
Or, to group them into Set
s use:
Map<String, Set<Apple>> sortedApples =
appleMap.values()
.stream()
.collect(Collectors.groupingBy(Apple::getColour,
Collectors.mapping(Function.identity(),
Collectors.toSet())));
add a comment |
You can use Collectors.groupingBy
and Collectors.toSet()
Map<String, Set<Apple>> sortedApples = appleMap.values() // Collection<Apple>
.stream() // Stream<Apple>
.collect(Collectors.groupingBy(Apple::getColour, // groupBy colour
Collectors.mapping(a -> a, Collectors.toSet()))); // collect to Set
add a comment |
if you want to proceed with toMap
you can get the result as follows:
map.entrySet()
.stream()
.collect(toMap(s -> s.getValue().getColour(),
v -> new HashSet<>(singleton(v.getValue())),
(l, r) -> {l.addAll(r); return l;}));
But I would not suggest it because as you can see this it is not very readable and not the idiomatic approach.
This is a job for the groupingBy
collector shown in the other answers or do it shorter without a stream:
Map<String, Set<Apple>> res = new HashMap<>();
map.forEach((k, v) -> res.computeIfAbsent(v.getColour(), e -> new HashSet<>()).add(v));
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%2f54005438%2fconvert-mapstring-object-to-mapstring-setobject-with-filter-and-streams%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Collectors.groupingBy
is more suitable than Collectors.toMap
for this task (though both can be used).
Map<String, List<Apple>> sortedApples =
appleMap.values()
.stream()
.collect(Collectors.groupingBy(Apple::getColour));
Or, to group them into Set
s use:
Map<String, Set<Apple>> sortedApples =
appleMap.values()
.stream()
.collect(Collectors.groupingBy(Apple::getColour,
Collectors.mapping(Function.identity(),
Collectors.toSet())));
add a comment |
Collectors.groupingBy
is more suitable than Collectors.toMap
for this task (though both can be used).
Map<String, List<Apple>> sortedApples =
appleMap.values()
.stream()
.collect(Collectors.groupingBy(Apple::getColour));
Or, to group them into Set
s use:
Map<String, Set<Apple>> sortedApples =
appleMap.values()
.stream()
.collect(Collectors.groupingBy(Apple::getColour,
Collectors.mapping(Function.identity(),
Collectors.toSet())));
add a comment |
Collectors.groupingBy
is more suitable than Collectors.toMap
for this task (though both can be used).
Map<String, List<Apple>> sortedApples =
appleMap.values()
.stream()
.collect(Collectors.groupingBy(Apple::getColour));
Or, to group them into Set
s use:
Map<String, Set<Apple>> sortedApples =
appleMap.values()
.stream()
.collect(Collectors.groupingBy(Apple::getColour,
Collectors.mapping(Function.identity(),
Collectors.toSet())));
Collectors.groupingBy
is more suitable than Collectors.toMap
for this task (though both can be used).
Map<String, List<Apple>> sortedApples =
appleMap.values()
.stream()
.collect(Collectors.groupingBy(Apple::getColour));
Or, to group them into Set
s use:
Map<String, Set<Apple>> sortedApples =
appleMap.values()
.stream()
.collect(Collectors.groupingBy(Apple::getColour,
Collectors.mapping(Function.identity(),
Collectors.toSet())));
answered 31 mins ago
Eran
279k37452537
279k37452537
add a comment |
add a comment |
You can use Collectors.groupingBy
and Collectors.toSet()
Map<String, Set<Apple>> sortedApples = appleMap.values() // Collection<Apple>
.stream() // Stream<Apple>
.collect(Collectors.groupingBy(Apple::getColour, // groupBy colour
Collectors.mapping(a -> a, Collectors.toSet()))); // collect to Set
add a comment |
You can use Collectors.groupingBy
and Collectors.toSet()
Map<String, Set<Apple>> sortedApples = appleMap.values() // Collection<Apple>
.stream() // Stream<Apple>
.collect(Collectors.groupingBy(Apple::getColour, // groupBy colour
Collectors.mapping(a -> a, Collectors.toSet()))); // collect to Set
add a comment |
You can use Collectors.groupingBy
and Collectors.toSet()
Map<String, Set<Apple>> sortedApples = appleMap.values() // Collection<Apple>
.stream() // Stream<Apple>
.collect(Collectors.groupingBy(Apple::getColour, // groupBy colour
Collectors.mapping(a -> a, Collectors.toSet()))); // collect to Set
You can use Collectors.groupingBy
and Collectors.toSet()
Map<String, Set<Apple>> sortedApples = appleMap.values() // Collection<Apple>
.stream() // Stream<Apple>
.collect(Collectors.groupingBy(Apple::getColour, // groupBy colour
Collectors.mapping(a -> a, Collectors.toSet()))); // collect to Set
edited 16 mins ago
answered 30 mins ago
nullpointer
42.5k1090175
42.5k1090175
add a comment |
add a comment |
if you want to proceed with toMap
you can get the result as follows:
map.entrySet()
.stream()
.collect(toMap(s -> s.getValue().getColour(),
v -> new HashSet<>(singleton(v.getValue())),
(l, r) -> {l.addAll(r); return l;}));
But I would not suggest it because as you can see this it is not very readable and not the idiomatic approach.
This is a job for the groupingBy
collector shown in the other answers or do it shorter without a stream:
Map<String, Set<Apple>> res = new HashMap<>();
map.forEach((k, v) -> res.computeIfAbsent(v.getColour(), e -> new HashSet<>()).add(v));
add a comment |
if you want to proceed with toMap
you can get the result as follows:
map.entrySet()
.stream()
.collect(toMap(s -> s.getValue().getColour(),
v -> new HashSet<>(singleton(v.getValue())),
(l, r) -> {l.addAll(r); return l;}));
But I would not suggest it because as you can see this it is not very readable and not the idiomatic approach.
This is a job for the groupingBy
collector shown in the other answers or do it shorter without a stream:
Map<String, Set<Apple>> res = new HashMap<>();
map.forEach((k, v) -> res.computeIfAbsent(v.getColour(), e -> new HashSet<>()).add(v));
add a comment |
if you want to proceed with toMap
you can get the result as follows:
map.entrySet()
.stream()
.collect(toMap(s -> s.getValue().getColour(),
v -> new HashSet<>(singleton(v.getValue())),
(l, r) -> {l.addAll(r); return l;}));
But I would not suggest it because as you can see this it is not very readable and not the idiomatic approach.
This is a job for the groupingBy
collector shown in the other answers or do it shorter without a stream:
Map<String, Set<Apple>> res = new HashMap<>();
map.forEach((k, v) -> res.computeIfAbsent(v.getColour(), e -> new HashSet<>()).add(v));
if you want to proceed with toMap
you can get the result as follows:
map.entrySet()
.stream()
.collect(toMap(s -> s.getValue().getColour(),
v -> new HashSet<>(singleton(v.getValue())),
(l, r) -> {l.addAll(r); return l;}));
But I would not suggest it because as you can see this it is not very readable and not the idiomatic approach.
This is a job for the groupingBy
collector shown in the other answers or do it shorter without a stream:
Map<String, Set<Apple>> res = new HashMap<>();
map.forEach((k, v) -> res.computeIfAbsent(v.getColour(), e -> new HashSet<>()).add(v));
edited 11 mins ago
answered 17 mins ago
Aomine
39.8k73770
39.8k73770
add a comment |
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.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- 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%2f54005438%2fconvert-mapstring-object-to-mapstring-setobject-with-filter-and-streams%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