Java 8: How to convert List to Map<String,List>?How to round a number to n decimal places in JavaHow do I read / convert an InputStream into a String in Java?How to convert a Map to List in Java?list comprehension vs. lambda + filterHow to convert an Array to a Set in JavaHow to avoid Java code in JSP files?How do I convert a String to an int in Java?Retrieving a List from a java.util.stream.Stream in Java 8Java 8 List<V> into Map<K, V>Convert Iterable to Stream using Java 8 JDK

What is this second smaller runway next to London City Airport?

Heat involved in isenthalpic process

Regular sized fonts in oubraces package

Simple code that checks if you're old enough to drive

Why is Eastern Switzerland called Suisse orientale in French?

Is CR12 too difficult for two level 4 characters?

How to apply a macro for every single matching pattern

Is there any algorithm that runs faster in Mathematica than in C or Fortran?

My bike's adjustable stem keeps falling down

How to capture a possible figure of speech with "E se io fossi vago" in translation?

Why does the SR-71 Blackbird sometimes have dents in the nose?

How does kinetic energy work in braking a vehicle?

Proof that if covariance is zero then there is no linear relationship

Create a program that prints the amount of characters it has, in words

Protecting Seals from Forgery

where does black come from in CMYK color mode?

I am particularly fascinated by the Chinese character that is pronounced SHIN & means faith or belief

why we need self-synchronization?

Why don't we say a blessing before giving charity?

How much caffeine would there be if I reuse tea leaves in a second brewing?

Can I take the high-speed bullet train Beijing–Hong Kong under Chinese 144 h visa-free transit rules?

How wavy is an array?

Command which removes data left side of ";" (semicolon) on each row

What do you call this when cats hunch their backs and their fur stands on end?



Java 8: How to convert List to Map>?


How to round a number to n decimal places in JavaHow do I read / convert an InputStream into a String in Java?How to convert a Map to List in Java?list comprehension vs. lambda + filterHow to convert an Array to a Set in JavaHow to avoid Java code in JSP files?How do I convert a String to an int in Java?Retrieving a List from a java.util.stream.Stream in Java 8Java 8 List<V> into Map<K, V>Convert Iterable to Stream using Java 8 JDK






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;









17

















I have a List of String like:



List<String> locations = Arrays.asList("US:5423","US:6321","CA:1326","AU:5631");


And I want to convert in Map<String, List<String>> as like:



AU = [5631]
CA = [1326]
US = [5423, 6321]


I have tried this code and it works but in this case, I have to create a new class GeoLocation.java.



List<String> locations=Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");
Map<String, List<String>> locationMap = locations
.stream()
.map(s -> new GeoLocation(s.split(":")[0], s.split(":")[1]))
.collect(
Collectors.groupingBy(GeoLocation::getCountry,
Collectors.mapping(GeoLocation::getLocation, Collectors.toList()))
);

locationMap.forEach((key, value) -> System.out.println(key + " = " + value));


GeoLocation.java



private class GeoLocation 
private String country;
private String location;

public GeoLocation(String country, String location)
this.country = country;
this.location = location;


public String getCountry()
return country;


public void setCountry(String country)
this.country = country;


public String getLocation()
return location;


public void setLocation(String location)
this.location = location;




But I want to know, Is there any way to convert List<String> to Map<String, List<String>> without introducing new class.










share|improve this question




























  • Java's lack of tuples strikes again :(

    – Alexander
    May 31 at 22:49

















17

















I have a List of String like:



List<String> locations = Arrays.asList("US:5423","US:6321","CA:1326","AU:5631");


And I want to convert in Map<String, List<String>> as like:



AU = [5631]
CA = [1326]
US = [5423, 6321]


I have tried this code and it works but in this case, I have to create a new class GeoLocation.java.



List<String> locations=Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");
Map<String, List<String>> locationMap = locations
.stream()
.map(s -> new GeoLocation(s.split(":")[0], s.split(":")[1]))
.collect(
Collectors.groupingBy(GeoLocation::getCountry,
Collectors.mapping(GeoLocation::getLocation, Collectors.toList()))
);

locationMap.forEach((key, value) -> System.out.println(key + " = " + value));


GeoLocation.java



private class GeoLocation 
private String country;
private String location;

public GeoLocation(String country, String location)
this.country = country;
this.location = location;


public String getCountry()
return country;


public void setCountry(String country)
this.country = country;


public String getLocation()
return location;


public void setLocation(String location)
this.location = location;




But I want to know, Is there any way to convert List<String> to Map<String, List<String>> without introducing new class.










share|improve this question




























  • Java's lack of tuples strikes again :(

    – Alexander
    May 31 at 22:49













17












17








17


3






I have a List of String like:



List<String> locations = Arrays.asList("US:5423","US:6321","CA:1326","AU:5631");


And I want to convert in Map<String, List<String>> as like:



AU = [5631]
CA = [1326]
US = [5423, 6321]


I have tried this code and it works but in this case, I have to create a new class GeoLocation.java.



List<String> locations=Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");
Map<String, List<String>> locationMap = locations
.stream()
.map(s -> new GeoLocation(s.split(":")[0], s.split(":")[1]))
.collect(
Collectors.groupingBy(GeoLocation::getCountry,
Collectors.mapping(GeoLocation::getLocation, Collectors.toList()))
);

locationMap.forEach((key, value) -> System.out.println(key + " = " + value));


GeoLocation.java



private class GeoLocation 
private String country;
private String location;

public GeoLocation(String country, String location)
this.country = country;
this.location = location;


public String getCountry()
return country;


public void setCountry(String country)
this.country = country;


public String getLocation()
return location;


public void setLocation(String location)
this.location = location;




But I want to know, Is there any way to convert List<String> to Map<String, List<String>> without introducing new class.










share|improve this question

















I have a List of String like:



List<String> locations = Arrays.asList("US:5423","US:6321","CA:1326","AU:5631");


And I want to convert in Map<String, List<String>> as like:



AU = [5631]
CA = [1326]
US = [5423, 6321]


I have tried this code and it works but in this case, I have to create a new class GeoLocation.java.



List<String> locations=Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");
Map<String, List<String>> locationMap = locations
.stream()
.map(s -> new GeoLocation(s.split(":")[0], s.split(":")[1]))
.collect(
Collectors.groupingBy(GeoLocation::getCountry,
Collectors.mapping(GeoLocation::getLocation, Collectors.toList()))
);

locationMap.forEach((key, value) -> System.out.println(key + " = " + value));


GeoLocation.java



private class GeoLocation 
private String country;
private String location;

public GeoLocation(String country, String location)
this.country = country;
this.location = location;


public String getCountry()
return country;


public void setCountry(String country)
this.country = country;


public String getLocation()
return location;


public void setLocation(String location)
this.location = location;




But I want to know, Is there any way to convert List<String> to Map<String, List<String>> without introducing new class.







java lambda java-8 java-stream






share|improve this question
















share|improve this question













share|improve this question




share|improve this question








edited Jun 3 at 7:11







Vinit Solanki

















asked May 31 at 6:12









Vinit SolankiVinit Solanki

9135 silver badges23 bronze badges




9135 silver badges23 bronze badges















  • Java's lack of tuples strikes again :(

    – Alexander
    May 31 at 22:49

















  • Java's lack of tuples strikes again :(

    – Alexander
    May 31 at 22:49
















Java's lack of tuples strikes again :(

– Alexander
May 31 at 22:49





Java's lack of tuples strikes again :(

– Alexander
May 31 at 22:49












5 Answers
5






active

oldest

votes


















24


















You may do it like so:



Map<String, List<String>> locationMap = locations.stream()
.map(s -> s.split(":"))
.collect(Collectors.groupingBy(a -> a[0],
Collectors.mapping(a -> a[1], Collectors.toList())));


A much more better approach would be,



private static final Pattern DELIMITER = Pattern.compile(":");

Map<String, List<String>> locationMap = locations.stream()
.map(s -> DELIMITER.splitAsStream(s).toArray(String[]::new))
.collect(Collectors.groupingBy(a -> a[0],
Collectors.mapping(a -> a[1], Collectors.toList())));


Update



As per the following comment, this can be further simplified to,



Map<String, List<String>> locationMap = locations.stream().map(DELIMITER::split)
.collect(Collectors.groupingBy(a -> a[0],
Collectors.mapping(a -> a[1], Collectors.toList())));





share|improve this answer























  • 3





    I don't see how the second approach is better. Can you please elaborate?

    – Michael A. Schaffrath
    May 31 at 6:39






  • 1





    I'm not sure this is correct. If you look at the source code of String.split you can see there's tons of optimization done for 1-char strings.

    – Michael A. Schaffrath
    May 31 at 6:51











  • The latter outperforms the former since it uses a pre-compiled pattern.

    – Ravindra Ranwala
    May 31 at 6:58






  • 4





    DELIMITER.splitAsStream(s).toArray(String[]::new) why not just use DELIMITER.split(s)?

    – Lino
    May 31 at 7:09






  • 7





    Strange result found when tried with 10 Million locations, pre-compiled pattern takes around 0.830 second and string split takes around the 0.58 second, much better approach is not the best approach from which you mentioned. So I using s -> s.split(":")

    – Vinit Solanki
    May 31 at 12:58



















3


















Try this



Map<String, List<String>> locationMap = locations.stream()
.map(s -> new AbstractMap.SimpleEntry<String,String>(s.split(":")[0], s.split(":")[1]))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));





share|improve this answer





















  • 1





    One can optimize the use of split twice there.

    – Naman
    May 31 at 6:20











  • @Naman, right! just copied OP answer....map(s->s.split(":")) .map(s -> new AbstractMap.SimpleEntry<String,String>(s[0],s[1]))... although @Ravindra Ranwala is better

    – Hadi J
    May 31 at 6:23



















3


















You can just put the code in grouping by part where you put first group as key and second as value instead of mapping it first



Map<String, List<String>> locationMap = locations
.stream()
.map(s -> s.split(":"))
.collect( Collectors.groupingBy( s -> s[0], Collectors.mapping( s-> s[1], Collectors.toList() ) ) );





share|improve this answer





















  • 1





    I noticed it after posting it

    – n1t4chi
    May 31 at 6:23


















2


















What about POJO. It looks not complicated comparing with streams.



public static Map<String, Set<String>> groupByCountry(List<String> locations) 
Map<String, Set<String>> map = new HashMap<>();

locations.forEach(location ->
String[] parts = location.split(":");
map.compute(parts[0], (country, codes) ->
codes = codes == null ? new HashSet<>() : codes;
codes.add(parts[1]);
return codes;
);
);

return map;






share|improve this answer



































    1


















    Seems like your location map needs to be sorted based on keys, you can try the following



    List<String> locations = Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");

    Map<String, List<String>> locationMap = locations.stream().map(str -> str.split(":"))
    .collect(() -> new TreeMap<String, List<String>>(), (map, parts) ->
    if (map.get(parts[0]) == null)
    List<String> list = new ArrayList<>();
    list.add(parts[1]);
    map.put(parts[0], list);
    else
    map.get(parts[0]).add(parts[1]);

    , (map1, map2) ->
    map1.putAll(map2);
    );

    System.out.println(locationMap); // this outputs AU=[5631], CA=[1326], US=[5423, 6321]





    share|improve this answer


























    • Sort doesn't matter in Map, The key and value should be present as like mentioned.

      – Vinit Solanki
      May 31 at 10:53












    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/4.0/"u003ecc by-sa 4.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%2f56389575%2fjava-8-how-to-convert-liststring-to-mapstring-liststring%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown


























    5 Answers
    5






    active

    oldest

    votes








    5 Answers
    5






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    24


















    You may do it like so:



    Map<String, List<String>> locationMap = locations.stream()
    .map(s -> s.split(":"))
    .collect(Collectors.groupingBy(a -> a[0],
    Collectors.mapping(a -> a[1], Collectors.toList())));


    A much more better approach would be,



    private static final Pattern DELIMITER = Pattern.compile(":");

    Map<String, List<String>> locationMap = locations.stream()
    .map(s -> DELIMITER.splitAsStream(s).toArray(String[]::new))
    .collect(Collectors.groupingBy(a -> a[0],
    Collectors.mapping(a -> a[1], Collectors.toList())));


    Update



    As per the following comment, this can be further simplified to,



    Map<String, List<String>> locationMap = locations.stream().map(DELIMITER::split)
    .collect(Collectors.groupingBy(a -> a[0],
    Collectors.mapping(a -> a[1], Collectors.toList())));





    share|improve this answer























    • 3





      I don't see how the second approach is better. Can you please elaborate?

      – Michael A. Schaffrath
      May 31 at 6:39






    • 1





      I'm not sure this is correct. If you look at the source code of String.split you can see there's tons of optimization done for 1-char strings.

      – Michael A. Schaffrath
      May 31 at 6:51











    • The latter outperforms the former since it uses a pre-compiled pattern.

      – Ravindra Ranwala
      May 31 at 6:58






    • 4





      DELIMITER.splitAsStream(s).toArray(String[]::new) why not just use DELIMITER.split(s)?

      – Lino
      May 31 at 7:09






    • 7





      Strange result found when tried with 10 Million locations, pre-compiled pattern takes around 0.830 second and string split takes around the 0.58 second, much better approach is not the best approach from which you mentioned. So I using s -> s.split(":")

      – Vinit Solanki
      May 31 at 12:58
















    24


















    You may do it like so:



    Map<String, List<String>> locationMap = locations.stream()
    .map(s -> s.split(":"))
    .collect(Collectors.groupingBy(a -> a[0],
    Collectors.mapping(a -> a[1], Collectors.toList())));


    A much more better approach would be,



    private static final Pattern DELIMITER = Pattern.compile(":");

    Map<String, List<String>> locationMap = locations.stream()
    .map(s -> DELIMITER.splitAsStream(s).toArray(String[]::new))
    .collect(Collectors.groupingBy(a -> a[0],
    Collectors.mapping(a -> a[1], Collectors.toList())));


    Update



    As per the following comment, this can be further simplified to,



    Map<String, List<String>> locationMap = locations.stream().map(DELIMITER::split)
    .collect(Collectors.groupingBy(a -> a[0],
    Collectors.mapping(a -> a[1], Collectors.toList())));





    share|improve this answer























    • 3





      I don't see how the second approach is better. Can you please elaborate?

      – Michael A. Schaffrath
      May 31 at 6:39






    • 1





      I'm not sure this is correct. If you look at the source code of String.split you can see there's tons of optimization done for 1-char strings.

      – Michael A. Schaffrath
      May 31 at 6:51











    • The latter outperforms the former since it uses a pre-compiled pattern.

      – Ravindra Ranwala
      May 31 at 6:58






    • 4





      DELIMITER.splitAsStream(s).toArray(String[]::new) why not just use DELIMITER.split(s)?

      – Lino
      May 31 at 7:09






    • 7





      Strange result found when tried with 10 Million locations, pre-compiled pattern takes around 0.830 second and string split takes around the 0.58 second, much better approach is not the best approach from which you mentioned. So I using s -> s.split(":")

      – Vinit Solanki
      May 31 at 12:58














    24














    24










    24









    You may do it like so:



    Map<String, List<String>> locationMap = locations.stream()
    .map(s -> s.split(":"))
    .collect(Collectors.groupingBy(a -> a[0],
    Collectors.mapping(a -> a[1], Collectors.toList())));


    A much more better approach would be,



    private static final Pattern DELIMITER = Pattern.compile(":");

    Map<String, List<String>> locationMap = locations.stream()
    .map(s -> DELIMITER.splitAsStream(s).toArray(String[]::new))
    .collect(Collectors.groupingBy(a -> a[0],
    Collectors.mapping(a -> a[1], Collectors.toList())));


    Update



    As per the following comment, this can be further simplified to,



    Map<String, List<String>> locationMap = locations.stream().map(DELIMITER::split)
    .collect(Collectors.groupingBy(a -> a[0],
    Collectors.mapping(a -> a[1], Collectors.toList())));





    share|improve this answer
















    You may do it like so:



    Map<String, List<String>> locationMap = locations.stream()
    .map(s -> s.split(":"))
    .collect(Collectors.groupingBy(a -> a[0],
    Collectors.mapping(a -> a[1], Collectors.toList())));


    A much more better approach would be,



    private static final Pattern DELIMITER = Pattern.compile(":");

    Map<String, List<String>> locationMap = locations.stream()
    .map(s -> DELIMITER.splitAsStream(s).toArray(String[]::new))
    .collect(Collectors.groupingBy(a -> a[0],
    Collectors.mapping(a -> a[1], Collectors.toList())));


    Update



    As per the following comment, this can be further simplified to,



    Map<String, List<String>> locationMap = locations.stream().map(DELIMITER::split)
    .collect(Collectors.groupingBy(a -> a[0],
    Collectors.mapping(a -> a[1], Collectors.toList())));






    share|improve this answer















    share|improve this answer




    share|improve this answer








    edited May 31 at 8:52

























    answered May 31 at 6:17









    Ravindra RanwalaRavindra Ranwala

    14.9k6 gold badges29 silver badges46 bronze badges




    14.9k6 gold badges29 silver badges46 bronze badges










    • 3





      I don't see how the second approach is better. Can you please elaborate?

      – Michael A. Schaffrath
      May 31 at 6:39






    • 1





      I'm not sure this is correct. If you look at the source code of String.split you can see there's tons of optimization done for 1-char strings.

      – Michael A. Schaffrath
      May 31 at 6:51











    • The latter outperforms the former since it uses a pre-compiled pattern.

      – Ravindra Ranwala
      May 31 at 6:58






    • 4





      DELIMITER.splitAsStream(s).toArray(String[]::new) why not just use DELIMITER.split(s)?

      – Lino
      May 31 at 7:09






    • 7





      Strange result found when tried with 10 Million locations, pre-compiled pattern takes around 0.830 second and string split takes around the 0.58 second, much better approach is not the best approach from which you mentioned. So I using s -> s.split(":")

      – Vinit Solanki
      May 31 at 12:58













    • 3





      I don't see how the second approach is better. Can you please elaborate?

      – Michael A. Schaffrath
      May 31 at 6:39






    • 1





      I'm not sure this is correct. If you look at the source code of String.split you can see there's tons of optimization done for 1-char strings.

      – Michael A. Schaffrath
      May 31 at 6:51











    • The latter outperforms the former since it uses a pre-compiled pattern.

      – Ravindra Ranwala
      May 31 at 6:58






    • 4





      DELIMITER.splitAsStream(s).toArray(String[]::new) why not just use DELIMITER.split(s)?

      – Lino
      May 31 at 7:09






    • 7





      Strange result found when tried with 10 Million locations, pre-compiled pattern takes around 0.830 second and string split takes around the 0.58 second, much better approach is not the best approach from which you mentioned. So I using s -> s.split(":")

      – Vinit Solanki
      May 31 at 12:58








    3




    3





    I don't see how the second approach is better. Can you please elaborate?

    – Michael A. Schaffrath
    May 31 at 6:39





    I don't see how the second approach is better. Can you please elaborate?

    – Michael A. Schaffrath
    May 31 at 6:39




    1




    1





    I'm not sure this is correct. If you look at the source code of String.split you can see there's tons of optimization done for 1-char strings.

    – Michael A. Schaffrath
    May 31 at 6:51





    I'm not sure this is correct. If you look at the source code of String.split you can see there's tons of optimization done for 1-char strings.

    – Michael A. Schaffrath
    May 31 at 6:51













    The latter outperforms the former since it uses a pre-compiled pattern.

    – Ravindra Ranwala
    May 31 at 6:58





    The latter outperforms the former since it uses a pre-compiled pattern.

    – Ravindra Ranwala
    May 31 at 6:58




    4




    4





    DELIMITER.splitAsStream(s).toArray(String[]::new) why not just use DELIMITER.split(s)?

    – Lino
    May 31 at 7:09





    DELIMITER.splitAsStream(s).toArray(String[]::new) why not just use DELIMITER.split(s)?

    – Lino
    May 31 at 7:09




    7




    7





    Strange result found when tried with 10 Million locations, pre-compiled pattern takes around 0.830 second and string split takes around the 0.58 second, much better approach is not the best approach from which you mentioned. So I using s -> s.split(":")

    – Vinit Solanki
    May 31 at 12:58






    Strange result found when tried with 10 Million locations, pre-compiled pattern takes around 0.830 second and string split takes around the 0.58 second, much better approach is not the best approach from which you mentioned. So I using s -> s.split(":")

    – Vinit Solanki
    May 31 at 12:58














    3


















    Try this



    Map<String, List<String>> locationMap = locations.stream()
    .map(s -> new AbstractMap.SimpleEntry<String,String>(s.split(":")[0], s.split(":")[1]))
    .collect(Collectors.groupingBy(Map.Entry::getKey,
    Collectors.mapping(Map.Entry::getValue, Collectors.toList())));





    share|improve this answer





















    • 1





      One can optimize the use of split twice there.

      – Naman
      May 31 at 6:20











    • @Naman, right! just copied OP answer....map(s->s.split(":")) .map(s -> new AbstractMap.SimpleEntry<String,String>(s[0],s[1]))... although @Ravindra Ranwala is better

      – Hadi J
      May 31 at 6:23
















    3


















    Try this



    Map<String, List<String>> locationMap = locations.stream()
    .map(s -> new AbstractMap.SimpleEntry<String,String>(s.split(":")[0], s.split(":")[1]))
    .collect(Collectors.groupingBy(Map.Entry::getKey,
    Collectors.mapping(Map.Entry::getValue, Collectors.toList())));





    share|improve this answer





















    • 1





      One can optimize the use of split twice there.

      – Naman
      May 31 at 6:20











    • @Naman, right! just copied OP answer....map(s->s.split(":")) .map(s -> new AbstractMap.SimpleEntry<String,String>(s[0],s[1]))... although @Ravindra Ranwala is better

      – Hadi J
      May 31 at 6:23














    3














    3










    3









    Try this



    Map<String, List<String>> locationMap = locations.stream()
    .map(s -> new AbstractMap.SimpleEntry<String,String>(s.split(":")[0], s.split(":")[1]))
    .collect(Collectors.groupingBy(Map.Entry::getKey,
    Collectors.mapping(Map.Entry::getValue, Collectors.toList())));





    share|improve this answer














    Try this



    Map<String, List<String>> locationMap = locations.stream()
    .map(s -> new AbstractMap.SimpleEntry<String,String>(s.split(":")[0], s.split(":")[1]))
    .collect(Collectors.groupingBy(Map.Entry::getKey,
    Collectors.mapping(Map.Entry::getValue, Collectors.toList())));






    share|improve this answer













    share|improve this answer




    share|improve this answer










    answered May 31 at 6:18









    Hadi JHadi J

    11.7k3 gold badges21 silver badges49 bronze badges




    11.7k3 gold badges21 silver badges49 bronze badges










    • 1





      One can optimize the use of split twice there.

      – Naman
      May 31 at 6:20











    • @Naman, right! just copied OP answer....map(s->s.split(":")) .map(s -> new AbstractMap.SimpleEntry<String,String>(s[0],s[1]))... although @Ravindra Ranwala is better

      – Hadi J
      May 31 at 6:23













    • 1





      One can optimize the use of split twice there.

      – Naman
      May 31 at 6:20











    • @Naman, right! just copied OP answer....map(s->s.split(":")) .map(s -> new AbstractMap.SimpleEntry<String,String>(s[0],s[1]))... although @Ravindra Ranwala is better

      – Hadi J
      May 31 at 6:23








    1




    1





    One can optimize the use of split twice there.

    – Naman
    May 31 at 6:20





    One can optimize the use of split twice there.

    – Naman
    May 31 at 6:20













    @Naman, right! just copied OP answer....map(s->s.split(":")) .map(s -> new AbstractMap.SimpleEntry<String,String>(s[0],s[1]))... although @Ravindra Ranwala is better

    – Hadi J
    May 31 at 6:23






    @Naman, right! just copied OP answer....map(s->s.split(":")) .map(s -> new AbstractMap.SimpleEntry<String,String>(s[0],s[1]))... although @Ravindra Ranwala is better

    – Hadi J
    May 31 at 6:23












    3


















    You can just put the code in grouping by part where you put first group as key and second as value instead of mapping it first



    Map<String, List<String>> locationMap = locations
    .stream()
    .map(s -> s.split(":"))
    .collect( Collectors.groupingBy( s -> s[0], Collectors.mapping( s-> s[1], Collectors.toList() ) ) );





    share|improve this answer





















    • 1





      I noticed it after posting it

      – n1t4chi
      May 31 at 6:23















    3


















    You can just put the code in grouping by part where you put first group as key and second as value instead of mapping it first



    Map<String, List<String>> locationMap = locations
    .stream()
    .map(s -> s.split(":"))
    .collect( Collectors.groupingBy( s -> s[0], Collectors.mapping( s-> s[1], Collectors.toList() ) ) );





    share|improve this answer





















    • 1





      I noticed it after posting it

      – n1t4chi
      May 31 at 6:23













    3














    3










    3









    You can just put the code in grouping by part where you put first group as key and second as value instead of mapping it first



    Map<String, List<String>> locationMap = locations
    .stream()
    .map(s -> s.split(":"))
    .collect( Collectors.groupingBy( s -> s[0], Collectors.mapping( s-> s[1], Collectors.toList() ) ) );





    share|improve this answer














    You can just put the code in grouping by part where you put first group as key and second as value instead of mapping it first



    Map<String, List<String>> locationMap = locations
    .stream()
    .map(s -> s.split(":"))
    .collect( Collectors.groupingBy( s -> s[0], Collectors.mapping( s-> s[1], Collectors.toList() ) ) );






    share|improve this answer













    share|improve this answer




    share|improve this answer










    answered May 31 at 6:20









    n1t4chin1t4chi

    3571 silver badge7 bronze badges




    3571 silver badge7 bronze badges










    • 1





      I noticed it after posting it

      – n1t4chi
      May 31 at 6:23












    • 1





      I noticed it after posting it

      – n1t4chi
      May 31 at 6:23







    1




    1





    I noticed it after posting it

    – n1t4chi
    May 31 at 6:23





    I noticed it after posting it

    – n1t4chi
    May 31 at 6:23











    2


















    What about POJO. It looks not complicated comparing with streams.



    public static Map<String, Set<String>> groupByCountry(List<String> locations) 
    Map<String, Set<String>> map = new HashMap<>();

    locations.forEach(location ->
    String[] parts = location.split(":");
    map.compute(parts[0], (country, codes) ->
    codes = codes == null ? new HashSet<>() : codes;
    codes.add(parts[1]);
    return codes;
    );
    );

    return map;






    share|improve this answer
































      2


















      What about POJO. It looks not complicated comparing with streams.



      public static Map<String, Set<String>> groupByCountry(List<String> locations) 
      Map<String, Set<String>> map = new HashMap<>();

      locations.forEach(location ->
      String[] parts = location.split(":");
      map.compute(parts[0], (country, codes) ->
      codes = codes == null ? new HashSet<>() : codes;
      codes.add(parts[1]);
      return codes;
      );
      );

      return map;






      share|improve this answer






























        2














        2










        2









        What about POJO. It looks not complicated comparing with streams.



        public static Map<String, Set<String>> groupByCountry(List<String> locations) 
        Map<String, Set<String>> map = new HashMap<>();

        locations.forEach(location ->
        String[] parts = location.split(":");
        map.compute(parts[0], (country, codes) ->
        codes = codes == null ? new HashSet<>() : codes;
        codes.add(parts[1]);
        return codes;
        );
        );

        return map;






        share|improve this answer
















        What about POJO. It looks not complicated comparing with streams.



        public static Map<String, Set<String>> groupByCountry(List<String> locations) 
        Map<String, Set<String>> map = new HashMap<>();

        locations.forEach(location ->
        String[] parts = location.split(":");
        map.compute(parts[0], (country, codes) ->
        codes = codes == null ? new HashSet<>() : codes;
        codes.add(parts[1]);
        return codes;
        );
        );

        return map;







        share|improve this answer















        share|improve this answer




        share|improve this answer








        edited Jun 1 at 6:08

























        answered May 31 at 7:31









        oleg.cherednikoleg.cherednik

        8,2422 gold badges12 silver badges19 bronze badges




        8,2422 gold badges12 silver badges19 bronze badges
























            1


















            Seems like your location map needs to be sorted based on keys, you can try the following



            List<String> locations = Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");

            Map<String, List<String>> locationMap = locations.stream().map(str -> str.split(":"))
            .collect(() -> new TreeMap<String, List<String>>(), (map, parts) ->
            if (map.get(parts[0]) == null)
            List<String> list = new ArrayList<>();
            list.add(parts[1]);
            map.put(parts[0], list);
            else
            map.get(parts[0]).add(parts[1]);

            , (map1, map2) ->
            map1.putAll(map2);
            );

            System.out.println(locationMap); // this outputs AU=[5631], CA=[1326], US=[5423, 6321]





            share|improve this answer


























            • Sort doesn't matter in Map, The key and value should be present as like mentioned.

              – Vinit Solanki
              May 31 at 10:53















            1


















            Seems like your location map needs to be sorted based on keys, you can try the following



            List<String> locations = Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");

            Map<String, List<String>> locationMap = locations.stream().map(str -> str.split(":"))
            .collect(() -> new TreeMap<String, List<String>>(), (map, parts) ->
            if (map.get(parts[0]) == null)
            List<String> list = new ArrayList<>();
            list.add(parts[1]);
            map.put(parts[0], list);
            else
            map.get(parts[0]).add(parts[1]);

            , (map1, map2) ->
            map1.putAll(map2);
            );

            System.out.println(locationMap); // this outputs AU=[5631], CA=[1326], US=[5423, 6321]





            share|improve this answer


























            • Sort doesn't matter in Map, The key and value should be present as like mentioned.

              – Vinit Solanki
              May 31 at 10:53













            1














            1










            1









            Seems like your location map needs to be sorted based on keys, you can try the following



            List<String> locations = Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");

            Map<String, List<String>> locationMap = locations.stream().map(str -> str.split(":"))
            .collect(() -> new TreeMap<String, List<String>>(), (map, parts) ->
            if (map.get(parts[0]) == null)
            List<String> list = new ArrayList<>();
            list.add(parts[1]);
            map.put(parts[0], list);
            else
            map.get(parts[0]).add(parts[1]);

            , (map1, map2) ->
            map1.putAll(map2);
            );

            System.out.println(locationMap); // this outputs AU=[5631], CA=[1326], US=[5423, 6321]





            share|improve this answer














            Seems like your location map needs to be sorted based on keys, you can try the following



            List<String> locations = Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");

            Map<String, List<String>> locationMap = locations.stream().map(str -> str.split(":"))
            .collect(() -> new TreeMap<String, List<String>>(), (map, parts) ->
            if (map.get(parts[0]) == null)
            List<String> list = new ArrayList<>();
            list.add(parts[1]);
            map.put(parts[0], list);
            else
            map.get(parts[0]).add(parts[1]);

            , (map1, map2) ->
            map1.putAll(map2);
            );

            System.out.println(locationMap); // this outputs AU=[5631], CA=[1326], US=[5423, 6321]






            share|improve this answer













            share|improve this answer




            share|improve this answer










            answered May 31 at 10:45









            chaitanya89chaitanya89

            5322 gold badges15 silver badges23 bronze badges




            5322 gold badges15 silver badges23 bronze badges















            • Sort doesn't matter in Map, The key and value should be present as like mentioned.

              – Vinit Solanki
              May 31 at 10:53

















            • Sort doesn't matter in Map, The key and value should be present as like mentioned.

              – Vinit Solanki
              May 31 at 10:53
















            Sort doesn't matter in Map, The key and value should be present as like mentioned.

            – Vinit Solanki
            May 31 at 10:53





            Sort doesn't matter in Map, The key and value should be present as like mentioned.

            – Vinit Solanki
            May 31 at 10:53


















            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%2f56389575%2fjava-8-how-to-convert-liststring-to-mapstring-liststring%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

            Tamil (spriik) Luke uk diar | Nawigatjuun

            Align equal signs while including text over equalitiesAMS align: left aligned text/math plus multicolumn alignmentMultiple alignmentsAligning equations in multiple placesNumbering and aligning an equation with multiple columnsHow to align one equation with another multline equationUsing \ in environments inside the begintabularxNumber equations and preserving alignment of equal signsHow can I align equations to the left and to the right?Double equation alignment problem within align enviromentAligned within align: Why are they right-aligned?

            Where does the image of a data connector as a sharp metal spike originate from?Where does the concept of infected people turning into zombies only after death originate from?Where does the motif of a reanimated human head originate?Where did the notion that Dragons could speak originate?Where does the archetypal image of the 'Grey' alien come from?Where did the suffix '-Man' originate?Where does the notion of being injured or killed by an illusion originate?Where did the term “sophont” originate?Where does the trope of magic spells being driven by advanced technology originate from?Where did the term “the living impaired” originate?