Reputation: 544
I have a list of model Config which looks like
class Config extends Model{
String name;
String type;
JsonNode config;
}
On querying the db, I get config for name 'abc' (which is passed by user) and id 'default'. There can be 3 config types (type1, type2, type3)
Requirement: If any config type is missing for the user input, config from 'default' is returned. For example: On querying for only name 'abc', I get
[
{
"name": "abc",
"type": "type1",
"config": []
},
{
"name": "abc",
"type": "type2",
"config": []
}
]
[
{
"name": "default",
"type": "type1",
"config": []
},
{
"name": "default",
"type": "type2",
"config": []
}
{
"name": "default",
"type": "type3",
"config": []
}
]
As config of type3 is missing response should be
[
{
"name": "abc",
"type": "type1",
"config": []
},
{
"name": "abc",
"type": "type2",
"config": []
},
{
"name": "default",
"type": "type3",
"config": []
}
]
What I have done:
I have a map <id, Config>. In a db query, I fetch Config for both id 1 and 0 in a list.
Map<String, JsonNode> customConfig = configList.stream()
.filter(o -> o.getOrgId().equals(1))
.collect(Collectors.toMap(Config::getKey, Config::getValue));
Map<String, JsonNode> defaultConfig = configList.stream()
.filter(o -> o.getId().equals(0))
.collect(Collectors.toMap(Config::getKey, Config::getValue));
And then I just do
configList.getOrDefault(type, defaultConfig.get(type));
What I want to do:
I want to merge the two streams into a single stream.
What I've tried: I looked into using groupingBy along with collectingAndThen in collectors but got confused on how to get the final result.
Upvotes: 1
Views: 130
Reputation: 106
If you are on the same method you can directly filter by the two options:
Map<String, JsonNode> customConfig = configList.stream()
.filter(o -> o.getOrgId().equals(1) || o.getOrgId().equals(0))
.collect(Collectors.toMap(Config::getKey, Config::getValue));
Another option is to return a stream and use the concat option:
Stream<Config> stream1 = configList.stream()
.filter(o -> o.getOrgId().equals(1));
Stream<Config> stream2 = configList.stream()
.filter(o -> o.getId().equals(0));
Map<String, JsonNode> config = Stream.concat(stream1, stream2)
.collect(Collectors.toMap(Config::getKey, Config::getValue));
Upvotes: 1