nested arraylist to hashmap in Java8 The Next CEO of Stack OverflowDifferences between HashMap and Hashtable?Java inner class and static nested classCreate ArrayList from arrayWhen to use LinkedList over ArrayList in Java?How do I break out of nested loops in Java?Initialization of an ArrayList in one lineIterate through a HashMapSort ArrayList of custom Objects by propertyDifference between HashMap, LinkedHashMap and TreeMapConvert ArrayList<String> to String[] array
pgfplots: How to draw a tangent graph below two others?
A hang glider, sudden unexpected lift to 25,000 feet altitude, what could do this?
Is a linearly independent set whose span is dense a Schauder basis?
Can I hook these wires up to find the connection to a dead outlet?
Why do we say “un seul M” and not “une seule M” even though M is a “consonne”?
Gödel's incompleteness theorems - what are the religious implications?
Free fall ellipse or parabola?
How to implement Comparable so it is consistent with identity-equality
Is it possible to create a QR code using text?
Another proof that dividing by 0 does not exist -- is it right?
Advance Calculus Limit question
Oldie but Goldie
How to pronounce fünf in 45
Is this a new Fibonacci Identity?
Is it reasonable to ask other researchers to send me their previous grant applications?
Creating a script with console commands
How did scripture get the name bible?
Why does the freezing point matter when picking cooler ice packs?
logical reads on global temp table, but not on session-level temp table
Is it "common practice in Fourier transform spectroscopy to multiply the measured interferogram by an apodizing function"? If so, why?
MT "will strike" & LXX "will watch carefully" (Gen 3:15)?
Can this transistor (2N2222) take 6 V on emitter-base? Am I reading the datasheet incorrectly?
How exploitable/balanced is this homebrew spell: Spell Permanency?
Small nick on power cord from an electric alarm clock, and copper wiring exposed but intact
nested arraylist to hashmap in Java8
The Next CEO of Stack OverflowDifferences between HashMap and Hashtable?Java inner class and static nested classCreate ArrayList from arrayWhen to use LinkedList over ArrayList in Java?How do I break out of nested loops in Java?Initialization of an ArrayList in one lineIterate through a HashMapSort ArrayList of custom Objects by propertyDifference between HashMap, LinkedHashMap and TreeMapConvert ArrayList<String> to String[] array
I have below Objects -
Company.java
private String compName;
private List<Department> departments;
Department.java
private String deptId;
private String deptName;
private List<Employee> employees;
Employee.java
private String empId;
private String legalStatement;
I want to return Map of each employee legal statement -
Map<String, String> legalStatement = new HashMap<>();
For that existing logic is -
for(Department department : departments)
if(department.getEmployees() != null &&
department.getEmployees().size() > 0)
for(Employee employee : department.getEmployees())
legalStatement.put(employee.getEmpId(),
employee.getLegalStatement());
How I can write same thing in Java 8 Stream API.
java java-8 java-stream
add a comment |
I have below Objects -
Company.java
private String compName;
private List<Department> departments;
Department.java
private String deptId;
private String deptName;
private List<Employee> employees;
Employee.java
private String empId;
private String legalStatement;
I want to return Map of each employee legal statement -
Map<String, String> legalStatement = new HashMap<>();
For that existing logic is -
for(Department department : departments)
if(department.getEmployees() != null &&
department.getEmployees().size() > 0)
for(Employee employee : department.getEmployees())
legalStatement.put(employee.getEmpId(),
employee.getLegalStatement());
How I can write same thing in Java 8 Stream API.
java java-8 java-stream
add a comment |
I have below Objects -
Company.java
private String compName;
private List<Department> departments;
Department.java
private String deptId;
private String deptName;
private List<Employee> employees;
Employee.java
private String empId;
private String legalStatement;
I want to return Map of each employee legal statement -
Map<String, String> legalStatement = new HashMap<>();
For that existing logic is -
for(Department department : departments)
if(department.getEmployees() != null &&
department.getEmployees().size() > 0)
for(Employee employee : department.getEmployees())
legalStatement.put(employee.getEmpId(),
employee.getLegalStatement());
How I can write same thing in Java 8 Stream API.
java java-8 java-stream
I have below Objects -
Company.java
private String compName;
private List<Department> departments;
Department.java
private String deptId;
private String deptName;
private List<Employee> employees;
Employee.java
private String empId;
private String legalStatement;
I want to return Map of each employee legal statement -
Map<String, String> legalStatement = new HashMap<>();
For that existing logic is -
for(Department department : departments)
if(department.getEmployees() != null &&
department.getEmployees().size() > 0)
for(Employee employee : department.getEmployees())
legalStatement.put(employee.getEmpId(),
employee.getLegalStatement());
How I can write same thing in Java 8 Stream API.
java java-8 java-stream
java java-8 java-stream
edited Mar 8 at 19:30
Naman
45.4k11102204
45.4k11102204
asked Mar 8 at 19:01
ppbppb
337827
337827
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
By using flatMap
and ternary
operator
Map<String,String> result = departments.stream()
.flatMap(d->(Objects.nonNull(d.getEmployees()) && !d.getEmployees().isEmpty()) ? d.getEmployees().stream() : Stream.empty())
.collect(Collectors.toMap(Employee::getEmpId, Employee::getLegalStatement));
As @nullpointer suggestion if there is a chance for duplicate employee id use mergeFunction
public static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper,
Function<? super T,? extends U> valueMapper,
BinaryOperator<U> mergeFunction)
If the mapped keys contains duplicates (according to Object.equals(Object)), the value mapping function is applied to each equal element, and the results are merged using the provided merging function.
add a comment |
You can use stream's filter
for if
, flatMap
for internal employee
list and collect
to collect as a Map
:
Map<String, String> legalStatement = departments.stream()
.filter(department -> department.getEmployees() != null && !department.getEmployees().isEmpty())
.flatMap(department -> department.getEmployees().stream())
.collect(Collectors.toMap(Employee::getEmpId, Employee::getLegalStatement));
In case there could beempld
s with multiple occurrences, you can write amergeFunction
within thecollect
to decide over what takes the preference.
– Naman
Mar 8 at 19:20
add a comment |
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%2f55069423%2fnested-arraylist-to-hashmap-in-java8%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
By using flatMap
and ternary
operator
Map<String,String> result = departments.stream()
.flatMap(d->(Objects.nonNull(d.getEmployees()) && !d.getEmployees().isEmpty()) ? d.getEmployees().stream() : Stream.empty())
.collect(Collectors.toMap(Employee::getEmpId, Employee::getLegalStatement));
As @nullpointer suggestion if there is a chance for duplicate employee id use mergeFunction
public static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper,
Function<? super T,? extends U> valueMapper,
BinaryOperator<U> mergeFunction)
If the mapped keys contains duplicates (according to Object.equals(Object)), the value mapping function is applied to each equal element, and the results are merged using the provided merging function.
add a comment |
By using flatMap
and ternary
operator
Map<String,String> result = departments.stream()
.flatMap(d->(Objects.nonNull(d.getEmployees()) && !d.getEmployees().isEmpty()) ? d.getEmployees().stream() : Stream.empty())
.collect(Collectors.toMap(Employee::getEmpId, Employee::getLegalStatement));
As @nullpointer suggestion if there is a chance for duplicate employee id use mergeFunction
public static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper,
Function<? super T,? extends U> valueMapper,
BinaryOperator<U> mergeFunction)
If the mapped keys contains duplicates (according to Object.equals(Object)), the value mapping function is applied to each equal element, and the results are merged using the provided merging function.
add a comment |
By using flatMap
and ternary
operator
Map<String,String> result = departments.stream()
.flatMap(d->(Objects.nonNull(d.getEmployees()) && !d.getEmployees().isEmpty()) ? d.getEmployees().stream() : Stream.empty())
.collect(Collectors.toMap(Employee::getEmpId, Employee::getLegalStatement));
As @nullpointer suggestion if there is a chance for duplicate employee id use mergeFunction
public static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper,
Function<? super T,? extends U> valueMapper,
BinaryOperator<U> mergeFunction)
If the mapped keys contains duplicates (according to Object.equals(Object)), the value mapping function is applied to each equal element, and the results are merged using the provided merging function.
By using flatMap
and ternary
operator
Map<String,String> result = departments.stream()
.flatMap(d->(Objects.nonNull(d.getEmployees()) && !d.getEmployees().isEmpty()) ? d.getEmployees().stream() : Stream.empty())
.collect(Collectors.toMap(Employee::getEmpId, Employee::getLegalStatement));
As @nullpointer suggestion if there is a chance for duplicate employee id use mergeFunction
public static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper,
Function<? super T,? extends U> valueMapper,
BinaryOperator<U> mergeFunction)
If the mapped keys contains duplicates (according to Object.equals(Object)), the value mapping function is applied to each equal element, and the results are merged using the provided merging function.
answered Mar 8 at 19:51
DeadpoolDeadpool
7,7572831
7,7572831
add a comment |
add a comment |
You can use stream's filter
for if
, flatMap
for internal employee
list and collect
to collect as a Map
:
Map<String, String> legalStatement = departments.stream()
.filter(department -> department.getEmployees() != null && !department.getEmployees().isEmpty())
.flatMap(department -> department.getEmployees().stream())
.collect(Collectors.toMap(Employee::getEmpId, Employee::getLegalStatement));
In case there could beempld
s with multiple occurrences, you can write amergeFunction
within thecollect
to decide over what takes the preference.
– Naman
Mar 8 at 19:20
add a comment |
You can use stream's filter
for if
, flatMap
for internal employee
list and collect
to collect as a Map
:
Map<String, String> legalStatement = departments.stream()
.filter(department -> department.getEmployees() != null && !department.getEmployees().isEmpty())
.flatMap(department -> department.getEmployees().stream())
.collect(Collectors.toMap(Employee::getEmpId, Employee::getLegalStatement));
In case there could beempld
s with multiple occurrences, you can write amergeFunction
within thecollect
to decide over what takes the preference.
– Naman
Mar 8 at 19:20
add a comment |
You can use stream's filter
for if
, flatMap
for internal employee
list and collect
to collect as a Map
:
Map<String, String> legalStatement = departments.stream()
.filter(department -> department.getEmployees() != null && !department.getEmployees().isEmpty())
.flatMap(department -> department.getEmployees().stream())
.collect(Collectors.toMap(Employee::getEmpId, Employee::getLegalStatement));
You can use stream's filter
for if
, flatMap
for internal employee
list and collect
to collect as a Map
:
Map<String, String> legalStatement = departments.stream()
.filter(department -> department.getEmployees() != null && !department.getEmployees().isEmpty())
.flatMap(department -> department.getEmployees().stream())
.collect(Collectors.toMap(Employee::getEmpId, Employee::getLegalStatement));
edited Mar 8 at 20:48
answered Mar 8 at 19:19
NamanNaman
45.4k11102204
45.4k11102204
In case there could beempld
s with multiple occurrences, you can write amergeFunction
within thecollect
to decide over what takes the preference.
– Naman
Mar 8 at 19:20
add a comment |
In case there could beempld
s with multiple occurrences, you can write amergeFunction
within thecollect
to decide over what takes the preference.
– Naman
Mar 8 at 19:20
In case there could be
empld
s with multiple occurrences, you can write a mergeFunction
within the collect
to decide over what takes the preference.– Naman
Mar 8 at 19:20
In case there could be
empld
s with multiple occurrences, you can write a mergeFunction
within the collect
to decide over what takes the preference.– Naman
Mar 8 at 19:20
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%2f55069423%2fnested-arraylist-to-hashmap-in-java8%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