Recently I stumbled on the need to split a list of values to lists of positive and negative numbers. However NOT one list positive and one for negative but basically beginning a new list once 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 it is something I am not really 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}; //0 -> ignore
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);
}
}
I think the reason for that is rather obvious: repeating major parts of the code. However I have no clue how I could export this way to a method to make the code a lot clearer.
Further, now that I saw the massive potential of streams I wondered whether there was a convenient way of writing this bulk using Java 8 Streams or using other Java 8 features to at least run parts of the code in a method.
Edit: This question was flagged to be a possible duplicate of Group sequences of values . Eventhough the title might tell differently the questions (at least from my perspective) are not duplicates. The linked one asks for groups of ascending values whereas mine asks for grouping by sign (positive/negative).