Getting ArraysIndexOutOfBoundException while trying to convert from list to map in java8

Viewed 62

I am trying to get Map<String,List<String>> from List<String> using split(), but I'm getting ArrayIndexOutOfBoundException.

List<String> lst = new ArrayList<>();
lst.add(A1);
lst.add(A2);
lst.add(A3);

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

results exception.

1 Answers

To avoid the exception, you should filter out arrays that don't have enough elements:

Map<String, List<String>> test1 = 
    lst.stream()
       .map(s -> s.split("[^A-Z]"))
       .filter(a -> a.length > 1)
       .map(a ->  new AbstractMap.SimpleEntry<String,String>(a[0],a[1]))
       .collect(Collectors.groupingBy(Map.Entry::getKey,
                                      Collectors.mapping(Map.Entry::getValue, 
                                                         Collectors.toList())));

BTW, there's no need to create the Map.Entrys. You can directly work with the arrays:

Map<String, List<String>> test1 = 
    lst.stream()
       .map(s -> s.split("[^A-Z]"))
       .filter(a -> a.length > 1)
       .collect(Collectors.groupingBy(a -> a[0],
                                      Collectors.mapping(a -> a[1], 
                                                         Collectors.toList())));
Related