簡體   English   中英

嘗試在java8中從列表轉換為映射時獲取ArraysIndexOutOfBoundException

[英]Getting ArraysIndexOutOfBoundException while trying to convert from list to map in java8

我正在嘗試使用split()List<String>獲取Map<String,List<String>> ,但我收到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())));

結果異常。

為避免異常,您應該過濾掉沒有足夠元素的數組:

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

順便說一句,沒有必要創建Map.Entry s。 您可以直接使用數組:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM