[SOLVED] Error with List.removeIf – Kth Largest Element in an Array


I am trying to find the Kth largest element in an array.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

class Solution {
    public int findKthLargest(int[] nums, int k) {
        //List<Integer> list = Arrays.asList(nums); 
        List<Integer> list = IntStream.of(nums).boxed().collect(Collectors.toList());
        int max = nums[0];

        for(int x = 1; x<=k; x++){
            for(int y = 1; y<list.size(); y++){
                int temp;
                if (nums[y] > max) {
                    max = nums[y];
                    temp = max;
        list.removeIf(value -> value.equals(temp.valueOf()));
    return max;

I am hit with the error:

Line 20: error: cannot find symbol
list.removeIf(value -> value.equals(temp.valueOf()));
symbol: variable temp
location: class Solution

And if I move int temp in between the two for loop statements, I get this error.

Line 21: error: int cannot be dereferenced
list.removeIf(value -> value.equals(temp.valueOf()));


If the task is just to find the K-th largest element, nothing should be removed from the list/array.

Just sort the array and return the k-th value counting from the end:

public static int findKthLargest(int[] nums, int k) {
    assert(k > 0 && k < nums.length); // make sure k is valid
    return nums[nums.length - k];

Answered By – Nowhere Man

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *