Java 8: How to convert List<String> to Map<String,List<String>>?

爷,独闯天下 提交于 2020-08-22 03:35:40

问题


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.


回答1:


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



回答2:


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



回答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() ) ) );



回答4:


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



回答5:


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]}


来源:https://stackoverflow.com/questions/56389575/java-8-how-to-convert-liststring-to-mapstring-liststring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!