-4

I want to ignore the ArrayIndexOutOfBoundsException: 0. I want to go further if the port1[1] is not empty.

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

I get this error at the first line of my code

java.lang.ArrayIndexOutOfBoundsException: 0

How do I skip this if the item I am pointing to is empty?

c.r
  • 43
  • 8
  • 5
    1. Don't ignore any exceptions in Java. 2. Please show us what `port1` contains – TheLostMind Nov 06 '18 at 23:26
  • I don't see a loop. – shmosel Nov 06 '18 at 23:29
  • @TheLostMind Currently its empty . In other cases I will have a string with key value pairs. – c.r Nov 06 '18 at 23:32
  • If `port1[1]` is not to cause an `ArrayIndexOutOfBoundsException`, then `port.length` must be 2 or greater. So you avoid the exception by amending your condition to include a test of that condition: `if (port1.length >= 2 && port[1] != null)...` Assuming, of course, that it's `if(port1[1] != null)` that's throwing the exception... – Kevin Anderson Nov 06 '18 at 23:33
  • verify what the value of `port1[1]` is – Scary Wombat Nov 07 '18 at 00:00

1 Answers1

2

You can "ignore ArrayIndexOutOfBoundsException: 0" by adding conditional logic to prevent it from happening.

In this case, it means that you want to check if result of s.split(":",2) is an array of 2 values, and ignore/skip if not. You do that by calling filter():

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())));
Andreas
  • 154,647
  • 11
  • 152
  • 247