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










1















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.










share|improve this question




























    1















    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.










    share|improve this question


























      1












      1








      1








      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.










      share|improve this question
















      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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 8 at 19:30









      Naman

      45.4k11102204




      45.4k11102204










      asked Mar 8 at 19:01









      ppbppb

      337827




      337827






















          2 Answers
          2






          active

          oldest

          votes


















          0














          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.







          share|improve this answer






























            0














            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));





            share|improve this answer

























            • In case there could be emplds with multiple occurrences, you can write a mergeFunction within the collect to decide over what takes the preference.

              – Naman
              Mar 8 at 19:20












            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
            );



            );













            draft saved

            draft discarded


















            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









            0














            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.







            share|improve this answer



























              0














              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.







              share|improve this answer

























                0












                0








                0







                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.







                share|improve this answer













                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.








                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 8 at 19:51









                DeadpoolDeadpool

                7,7572831




                7,7572831























                    0














                    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));





                    share|improve this answer

























                    • In case there could be emplds with multiple occurrences, you can write a mergeFunction within the collect to decide over what takes the preference.

                      – Naman
                      Mar 8 at 19:20
















                    0














                    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));





                    share|improve this answer

























                    • In case there could be emplds with multiple occurrences, you can write a mergeFunction within the collect to decide over what takes the preference.

                      – Naman
                      Mar 8 at 19:20














                    0












                    0








                    0







                    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));





                    share|improve this answer















                    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));






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Mar 8 at 20:48

























                    answered Mar 8 at 19:19









                    NamanNaman

                    45.4k11102204




                    45.4k11102204












                    • In case there could be emplds 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 emplds 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 emplds 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 emplds with multiple occurrences, you can write a mergeFunction within the collect to decide over what takes the preference.

                    – Naman
                    Mar 8 at 19:20


















                    draft saved

                    draft discarded
















































                    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.




                    draft saved


                    draft discarded














                    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





















































                    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







                    Popular posts from this blog

                    Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                    2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                    Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme