Recently, I came across the need to split a list of values ββinto lists of positive and negative numbers. However, NOT one list is positive and one for the negative, but basically a new list starts after the sign changes (ignoring 0 values);
Example:
valuesInList = [-1, -3, -5, -120, 0, 15, 24, 42, 13, -15, -24, -42, 1, 2, 3]
splitList = [[-1, -3, -5, -120], [15, 24, 42, 13], [-15, -24, -42], [1, 2, 3]]
I wrote code that works, but this is what I'm not very happy with:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Byte[] values = new Byte[]{-1, -3, -5, -120, 0, 15, 24, 42, 13, -15, -24, -42, 1, 2, 3};
List<Byte> valuesInList = Arrays.asList(values);
System.out.println("valuesInList = " + valuesInList);
int firstNotZero = valuesInList.stream().filter(b -> b != 0).collect(Collectors.toList()).get(0);
boolean currentlyLookingForPositive = firstNotZero > 0;
List<List<Byte>> splitList = new ArrayList<>();
int index = 0;
while (index < valuesInList.size()) {
List<Byte> collection = new ArrayList<>();
while (currentlyLookingForPositive && index < valuesInList.size()) {
byte current = valuesInList.get(index);
if (current > 0) {
collection.add(current);
index++;
}
else
currentlyLookingForPositive = false;
if (current == 0)
index++;
}
if (!collection.isEmpty())
splitList.add(collection);
collection = new ArrayList<>();
while (!currentlyLookingForPositive && index < valuesInList.size()) {
byte current = valuesInList.get(index);
if (current < 0) {
collection.add(current);
index++;
}
else
currentlyLookingForPositive = true;
}
if (!collection.isEmpty())
splitList.add(collection);
}
System.out.println("splitList = " + splitList);
}
}
, : . , , .
, , , , Java 8 Java 8, .
: . , - , ( , ) . , (/).