WazW111 WazW111 - 1 year ago 88
Java Question

Negative subarrays Java 8

I'm solving some task from java at hackerrank.com. The task is to give the number of negative subarrays.
On the input: The first line consists an integer n. The next line will contain n space separated integers.
On the output: print number of negative subarrays.

A sub-array is "Negative" if sum of all the integers in that sub-array is negative.

(link for the task: https://www.hackerrank.com/challenges/java-1d-array-easy)

I'm trying to solve this task using Java 8 feats. I've written the code that passes all tests and solves this task. However, I'm wondering if it's possible to refactor this code to use only one stream operation. In other words, I'm wondering how to write sth like:

long result = Arrays.asList(....)
.filter(sum -> sum < 0)

My solution:

public class Solution01 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
String s = sc.nextLine();

List<Integer> nums = Arrays.asList(s.split(" ")).stream()

long result = getAllSubarrays(nums)
.map(num -> mySum(num))
.filter(sum -> sum < 0)


public static Stream<List<Integer>> getAllSubarrays(List<Integer> array){
List<List<Integer>> nums = new ArrayList<>();
List<Integer> num;

for(int i = 0; i < array.size(); i++){
for(int j = i; j < array.size(); j++){
num = new ArrayList<>();
for(int k = i; k <= j; k++){

return nums.stream();

public static Integer mySum(List<Integer> nums){
int sum = 0;
for(int i = 0; i < nums.size(); i++)
sum += nums.get(i);

return sum;

PS. I make no use of first line of input :)


Try this.

long result = IntStream.range(0, nums.size())
    .flatMap(from -> IntStream.range(from + 1, nums.size() + 1)
        .map(to -> nums.subList(from, to).stream()
            .mapToInt(i -> i)
    .filter(sum -> sum < 0)