collect 方法时如何忽略 ArrayIndexOutOfBoundsException: 0?

我想忽略 ArrayIndexOutOfBoundsException: 0。如果 port1[1] 不为空,我想更进一步。


if (port1[1] != null){

    String[] inputArray1=port1[1].split(",");


    Map meInputs1 = Stream.of(inputArray1)

                          .map(s -> s.split(":",2))

                          .collect(Collectors.groupingBy(s -> s[0],  

                                   Collectors.mapping(s -> s[1], 

                                   Collectors.toList()))); 

    }

我在代码的第一行收到此错误


java.lang.ArrayIndexOutOfBoundsException: 0

如果我指向的项目是空的,我该如何跳过这个?


守着一只汪
浏览 266回答 1
1回答

牧羊人nacy

您可以通过添加条件逻辑来“忽略 ArrayIndexOutOfBoundsException: 0”以防止它发生。在这种情况下,这意味着您要检查结果s.split(":",2)是否为 2 个值的数组,如果不是,则忽略/跳过。你可以通过调用来做到这一点filter():Map<Object, List<Object>> meInputs1 = Stream.of(inputArray1)&nbsp; &nbsp; &nbsp; &nbsp; .map(s -> s.split(":",2))&nbsp; &nbsp; &nbsp; &nbsp; .filter(s -> s.length >= 2) // ignore entries in inputArray1 without a ':'&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.groupingBy(s -> s[0],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Collectors.mapping(s -> s[1],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Collectors.toList())));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java