2

I'm trying to sort an ArrayList by two criterias: ascending in both row and col. I'm getting the following error:

Multiple markers at this line
    - Syntax error on tokens, delete these tokens
    - The method RowColElem() is undefined for the type 
     DenseBoard<T>
    - The method RowColElem() is undefined for the type 
     DenseBoard<T>
    - Syntax error on tokens, delete these tokens

Here's a simplified version of my code:

public class DenseBoard<T>{

    private ArrayList<RowColElem<T>> tempDiagList;

    public void foo() {
        Collections.sort(tempDiagList, Comparator.comparingInt(RowColElem::getRow())
                                                 .thenComparingInt(RowColElem::getCol()));
    }
}
7
  • 1
    Remove the parenthesis at RowColElem::getRow() and RowColElem::getCol(). Commented Sep 20, 2015 at 18:08
  • Still the same. I did RowColElem::getRow and RowColElem::getCol but sill getting errors. Multiple markers at this line - RowColElem cannot be resolved to a variable - Syntax error on tokens, delete these tokens - Syntax error on tokens, delete these tokens - RowColElem cannot be resolved to a variable Commented Sep 20, 2015 at 18:11
  • 1
    Are you sure you're compiling with Java 8? Are you using an IDE? Commented Sep 20, 2015 at 18:12
  • 1
    Then try to reduce your example to a minimal one. There's too much code in your post. Commented Sep 20, 2015 at 18:13
  • 1
    I edited your post to remove all the unnecessary code so that it is easier to see the real problem. Commented Sep 20, 2015 at 18:27

1 Answer 1

3

The first problem with your code comes from the extra parentheses in RowColElem::getRow() and RowColElem::getCol(). This is called a method reference (section 15.13 of the JLS for the details).

Then, the real issue here is that the Java compiler cannot infer the correct type of the element in the lambda expression of comparingInt and it defaults to Object.

You have to specify the type of the expected element like this:

Collections.sort(list, Comparator.<RowColElem<T>> comparingInt(RowColElem::getRow)
                                                 .thenComparingInt(RowColElem::getCol));

Another solution would be to use a local assignment:

Comparator<RowColElem<T>> comparator = Comparator.comparingInt(RowColElem::getRow);
List<RowColElem<T>> list = new ArrayList<>();
Collections.sort(list, comparator.thenComparingInt(RowColElem::getCol));
Sign up to request clarification or add additional context in comments.

3 Comments

I hate saying this but its giving me the same very error. It says RowColElem cannot be assigned to a variable, @Tunaki
Did you copy the first snippet of code without typo? I just tested and it works.
No need to use Collections.sort(list, comparator) in Java-8. Just call list.sort(comparator).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.