Method sort type Collections not applicable for arguments comparator

Method sort type Collections not applicable for arguments comparator

OR
The method sort(List, Comparator<? super T>) in the type Collections is not applicable for the arguments (List, new Comparator<List>(){})

If see above exception it means you try to use Collections.sort operation using Comparator as second parameter and not implements Comparator interface and override its compare method.

Below class will give compilation error The method sort(List, Comparator<? super T>) in the type Collections is not applicable for the arguments (List, new Comparator<List>(){}):

package com.javahonk.algorithms;

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

public class SortingTestIssue {

	public static void main(String[] args) {

	List<Integer> list = new ArrayList<Integer>();
	list.add(1);
	list.add(5);
	list.add(3);
	list.add(4);
	list.add(2);

	System.out.println("Unsorted list: " + list);
	// Sort list in descending order

	Collections.sort(list, new Comparator<List<Integer>>() {
	public int compare(List<Integer> o1, List<Integer> o2) {
		return ((Number) o2).intValue() - ((Number) o1).intValue();
	}
	});
	}

}

 

Solution: Below is fix for above class:

package com.javahonk.algorithms;

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

public class SortingTestIssue implements Comparator<Integer> {

	public static void main(String[] args) {

	List<Integer> list = new ArrayList<Integer>();
	list.add(1);
	list.add(5);
	list.add(3);
	list.add(4);
	list.add(2);

	System.out.println("Unsorted list: " + list);
	// Sort list in descending order
	Collections.sort(list, new SortingTestIssue());
	System.out.println("\nSorted list descending order: " + list);
	}

	@Override
	public int compare(Integer o1, Integer o2) {
		return o2.intValue() - o1.intValue();
	}

}

 

Output:

Method sort type Collections not applicable for arguments comparator

Leave a Reply

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