Skip to content
Advertisement

How to return arraylist vertically

I am trying to return an array list vertically but I’m having some issues trying to implement it. Below is my code, and the return results; Output is what I’m trying to get to be vertically

public static List<Integer> predictAnswer(List<Integer> stockData, List<Integer> queries) {
// Write your code here

//Declare list for storing result
List<Integer> result = new ArrayList<Integer>();
//Declare variable for storing index of previous and next smaller stock
int previousNear = -1, nextNear =-1;

for (int query : queries){
    // Reset previousNear and nextNear values
    previousNear = nextNear = -1;
    
    //Iterate and find smaller stock to first day; previousNear reamians -1 if smaller stock not found
    for (int day = query - 1; day>= 0; day--){
        if (stockData.get(query - 1) > stockData.get(day)){
            previousNear = day;
            break;
        }
    }
   //Iterate and find smaller stock to last day; nextNear remains -1 if smaller stock not   found
   for (int day = query; day < stockData.size(); day++) {
       
       if (stockData.get(query -1 ) > stockData.get(day)){
           nextNear = day;
           break;
       }
       
   }
   if (previousNear == -1 && nextNear == -1)
        result.add(-1);
        
    else if (previousNear == -1 && nextNear!= -1)
    result.add(nextNear + 1);
    else if (query - previousNear - 1 > nextNear - query + 1)
        result.add(nextNear + 1);
        else result.add(previousNear + 1);
    

}

return result;
    }

}

My current output is [2, 4, -1]

I’d like it to be

2
4
-1

Any help would be appreciated. Thank you in advance

Advertisement

Answer

Hi if you mean to display each value from results on new line you can do this :

 public static void display() {
    List<Integer> results = List.of(1, 2, 46);
    for (Integer result : results) {
        System.out.println(result);
    }
}

See this code run live at Ideone.com.

1
2
46

Or, use streams to iterate each element of the list, using a method reference to print.

List
    .of( 1, 2, 46 )
    .stream()
    .forEach( System.out :: println ) ;

Same result.

Advertisement