Java 如何在使用.map和.collect方法时忽略ArrayIndexOutOfBoundsException:0?
我想忽略ArrayIndexOutOfBoundsException:0。如果端口1[1]不是空的,我想更进一步Java 如何在使用.map和.collect方法时忽略ArrayIndexOutOfBoundsException:0?,java,Java,我想忽略ArrayIndexOutOfBoundsException:0。如果端口1[1]不是空的,我想更进一步 if (port1[1] != null){ String[] inputArray1=port1[1].split(","); Map meInputs1 = Stream.of(inputArray1) .map(s -> s.split(":",2))
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
如果我指向的项为空,如何跳过此操作?您可以通过添加条件逻辑来防止发生“忽略ArrayIndexOutOfBoundsException:0”
在本例中,这意味着您要检查s.split(“:”,2)
的结果是否是一个包含2个值的数组,如果不是,则忽略/跳过。您可以通过拨打以下电话:
Map meInputs1=Stream.of(inputArray1)
.map(s->s.split(“:”,2))
.filter(s->s.length>=2)//忽略inputArray1中不带“:”的条目
.collect(收集器.groupingBy->s[0],
Collectors.mapping(s->s[1],
收藏家;
1。不要忽略Java中的任何异常。2.请告诉我们端口1包含的内容我没有看到循环。@LastMind当前为空。在其他情况下,我将有一个带有键值对的字符串。如果port1[1]
不会导致ArrayIndexOutOfBoundsException
,则port.length
必须为2或更大。因此,您可以通过修改条件以包含对该条件的测试来避免异常:if(port1.length>=2&&port[1]!=null).
当然,假设引发异常的是if(port1[1]!=null)
,请验证port1[1]
的值
Map<Object, List<Object>> meInputs1 = Stream.of(inputArray1)
.map(s -> s.split(":",2))
.filter(s -> s.length >= 2) // ignore entries in inputArray1 without a ':'
.collect(Collectors.groupingBy(s -> s[0],
Collectors.mapping(s -> s[1],
Collectors.toList())));