Questions tagged [comparator]

A Common interface to create an object that specifies the way of comparing other objects. When using this tag on implementation heavy questions - tag the code language the implementation is written in.

976
votes
24answers
935k views

Sort ArrayList of custom Objects by property

I read about sorting ArrayLists using a Comparator but in all of the examples people used compareTo which according to some research is a method for Strings.I wanted to sort an ArrayList of custom ...
153
votes
10answers
153k views

“Comparison method violates its general contract!”

Can someone explain me in simple terms, why does this code throw an exception, "Comparison method violates its general contract!", and how do I fix it?private int compareParents(Foo s1, Foo s2) {...
138
votes
10answers
418k views

How to use Comparator in Java to sort

I learned how to use the comparable but I'm having difficulty with the Comparator. I am having a error in my code: Exception in thread "main" java.lang.ClassCastException: New.People cannot be cast ...
52
votes
7answers
97k views

Java error: Comparison method violates its general contract

I saw many questions about this, and tried to solve the problem, but after one hour of googling and a lots of trial & error, I still can't fix it. I hope some of you catch the problem.This is ...
114
votes
11answers
169k views

When should a class be Comparable and/or Comparator? [closed]

I have seen classes which implement both Comparable and Comparator. What does this mean? Why would I use one over the other?
94
votes
19answers
93k views

When to use Comparable and Comparator

I have a list of objects I need to sort on a field, say Score. Without giving much thought I wrote a new class that implements Comparator, that does the task and it works. Now looking back at this, ...
67
votes
8answers
61k views

Natural sort order string comparison in Java - is one built in? [duplicate]

I'd like some kind of string comparison function that preserves natural sort order1. Is there anything like this built into Java? I can't find anything in the String class, and the Comparator class ...
126
votes
2answers
162k views

Java : Comparable vs Comparator [duplicate]

Possible Duplicates:difference between compare() and compareTo()Java: What is the difference between implementing Comparable and Comparator? What are the keys differences between Comparable ...
59
votes
5answers
22k views

How does Javascript's sort() work?

How does the following code sort this array to be in numerical order? var array=[25, 8, 7, 41]array.sort(function(a,b){return a - b})I know that if the result of the computation is... ...
83
votes
10answers
151k views

Android-java- How to sort a list of objects by a certain value within the object

Im trying to sort through an arraylist of objects by a particular value within the object. What would be the best approach to do such a thing. Should I use Collections.sort() with some kind of ...
48
votes
7answers
11k views

Sorting Java objects using multiple keys

I've got a collection of Duck objects and I'd like to sort them using multiple keys.class Duck {DuckAge age; //implements ComparableDuckWeight weight; //implements ComparableString ...
26
votes
2answers
76k views

Java Comparator class to sort arrays

Say, we have the following 2-dimensional array:int camels[][]=new int[n][2];How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order using ...
60
votes
4answers
23k views

Very confused by Java 8 Comparator type inference

I've been looking at the difference between Collections.sort and list.sort, specifically regarding using the Comparator static methods and whether param types are required in the lambda expressions. ...
23
votes
3answers
87k views

Java TreeMap Comparator

I need a comparator for a TreeMap. Should I write this anonymously in the constructor for my TreeMap? How else could I write my comparator. Currently, Java does not like my code (can I do this ...
10
votes
4answers
2k views

PriorityQueue.toString wrong element order

I am trying to make a priority queue in java with the nodes with the lowest frequency in priority. However, my comparator is not working and the output is very weird. I believe I need to change my ...
35
votes
3answers
16k views

Comparable and Comparator contract with regards to null

Comparable contract specifies that e.compareTo(null) must throw NullPointerException.From the API:Note that null is not an instance of any class, and e.compareTo(null) should throw a ...
6
votes
5answers
13k views

Using Comparable for multiple dynamic fields of VO in java

I have a classpublic class StudentVO {int age;String name; }I used the same class in two different areas. At one place i need to sort based on the age. In another place I need to sort ...
14
votes
7answers
25k views

why does my compare method throw exception — Comparison method violates its general contract!

Why does this code public class SponsoredComparator implements Comparator<SRE> {public boolean equals(SRE arg0, SRE arg1){return arg0.getSponsored()==arg1.getSponsored();}...
18
votes
2answers
34k views

Reverse a comparator in Java 8

I have an ArrayList and want sort it in descending order. I use for it java.util.stream.Stream.sorted(Comparator) method. Here is a description according Java API:Returns a stream consisting of ...
3
votes
4answers
2k views

Java - Sort Strings like Windows Explorer

I am trying to use code suggested by Sander Pham on another question. I need my java ArrayList of string names to be sorted like Windows Explorer does. His code worked for everything but for one ...
25
votes
3answers
4k views

Java generics: Collections.max() signature and Comparator

I understand the get and put principle for collections: if a method takes in a collection that it will write a type T to, the parameter has to be Collection<? super T>, whereas if it will read a ...
36
votes
5answers
107k views

Simple way to sort strings in the (case sensitive) alphabetical order

I need to sort list of strings in the alphabetical order:List<String> list=new ArrayList();list.add("development");list.add("Development");list.add("aa");list.add("AA");list.add("Aa");...
11
votes
2answers
43k views

How to sort ArrayList using Comparator? [duplicate]

I have a Class Student that Implements a static method public static Comparator<Student> getCompByName()that returns a new comparator object for Student that compares 2 Students objects by ...
41
votes
1answer
9k views

null-safe mapping Comparator using default implementations

Is there a build-in possibility to create a null-safe mapping comparator in Java 8 without writing a own implementation of Comparator?When running the following code, it causes a NPE because the ...
8
votes
3answers
18k views

Java 8 Comparator nullsFirst naturalOrder confused

this may be a simple question but I would like to understand it clearly...I have a code like this:public final class Persona{private final int id;private final String namepublic ...
35
votes
9answers
58k views

Comparator with double type

I have written the following code:public class NewClass2 implements Comparator<Point>{public int compare(Point p1, Point p2){return (int)(p1.getY() - p2.getY());}}...
13
votes
1answer
14k views

compare object properties and show diff in PHP

I'm searching for a way to show me the different properties/values from given objects...$obj1=new StdClass; $obj1->prop=1;$obj2=new StdClass; $obj2->prop=2;var_dump(array_diff((...
5
votes
3answers
4k views

Why does the Java Collections Framework offer two different ways to sort?

If I have a list of elements I would like to sort, Java offers two ways to go about this. For example, lets say I have a list of Movie objects and I’d like to sort them by title.One way I could ...
4
votes
5answers
39k views

Java: SortedMap, TreeMap, Comparable? How to use?

I have a list of objects I need to sort according to properties of one of their fields. I've heard that SortedMap and Comparators are the best way to do this.Do I implement Comparable with the class ...
10
votes
3answers
4k views

Comparator.comparing(…) of a nested field

Suppose I have a domain model like this:class Lecture {Course course;... // getters}class Course {Teacher teacher;int studentSize;... // getters}class Teacher {...
19
votes
2answers
36k views

Create a SortedMap in Java with a custom Comparator

I want to create a TreeMap in Java with a custom sort order. The sorted keys which are string need to be sorted according to the second character. The values are also string.Sample map:Za,FOOAb,...
48
votes
9answers
40k views

comparator with null values

We have some code wich sorts a list of addresses based on the distance between their coordinates. this is done through collections.sort with a custom comparator.However from time to time an adress ...
14
votes
2answers
32k views

STL Priority Queue on custom class

I'm having a lot of trouble getting my priority queue to recognize which parameter it should sort by. I've overloaded the less than operator in my custom class but it doesn't seem to use it. Here's ...
22
votes
6answers
120k views

java comparator, how to sort by integer?

Im trying to learn comparator in java and I have found this great example online, my question is how would this code be changed so that the pet names are ordered by age and in descending order so that ...
35
votes
13answers
39k views

What's the difference between “LIKE” and “=” in SQL?

Is there any difference between:SELECT * FROM users WHERE username="davyjones"andSELECT * FROM users WHERE username LIKE "davyjones"(I think I've bungled up the syntax... pardon me for that,I'...
13
votes
2answers
52k views

Implementing Java Comparator

I am trying to write an algorithm which utilizes a min-priority queue, so I looked around on google and found the PriorityQueue. It seems that in order to use it, though, I am going to need to tell it ...
4
votes
6answers
88k views

how to sort an ArrayList in ascending order using Collections and Comparator

How to sort an ArrayList in ascending order using Comparator? I know how to sort it in descending order using: Comparator mycomparator=Collections.reverseOrder();thenCollections.sort(...
6
votes
6answers
8k views

How to use Java comparator properly?

If I have the following class:public class Employee {private int empId;private String name;private int age;public Employee(int empId, String name, int age) {// set ...
5
votes
2answers
2k views

Making a Java PriorityQueue into a stable priority queue

I'm trying to implement a stable (first in first out) priority queue in Java. Supposing that the key is a name and the value is an age, I know I can make an unstable priority queue like this:Queue&...
2
votes
1answer
7k views

Comparison method violates its general contract Exception

Below is a block of code that results in exception as indicated,Code :Collections.sort( arrayList, new Comparator() {public int compare( Object o1, Object o2 ){TypeAdapterSort ...
25
votes
8answers
4k views

Why does Comparator declare equals?

The Comparator interface has its own equals() method. Any class will get equals() by default through Object class. What is the need to have equals() method inside an interface?
10
votes
11answers
22k views

Comparator and equals()

Suppose I need TreeSet with elements sorted with some domain logic. By this logic it doesn't matter order of some elements that doesn't equal so compare method can return 0, but in this case I couldn'...
19
votes
6answers
13k views

Java, Why it is implied that objects are equal if compareTo() returns 0?

Let's have a class Person. Person has a name and height.Equals and hashCode() takes into account only name. Person is comparable (or we implement comparator for it, does not matter which one). ...
9
votes
4answers
23k views

Java Map sort by value

I was looking for ways of sorting Map<String, Integer> by values. I found this post, which solved my sorting problem, but not exactly. According to the post, I wrote the following code:import ...
4
votes
3answers
8k views

Comparable and Comparator Interface in Java

I want to write a generic Pair class, which has two members: key and value. The only requirement to this class is that both key and value should implements the Comparable interface, otherwise Pair ...
10
votes
2answers
11k views

Why Comparator.comparing doesn't work with String::toLowerCase method reference?

I am trying to sort an array of Strings by reverse order (ignoring case), without modifying it, and just printing it. So I am using Java8 stream. But I can't manage to do it.Here is my attempt :...
4
votes
3answers
2k views

Java comparator for String in EBCDIC encoding

I have come across a requirement where I need to convert a string to EBCDIC encoding and then sort it. We need to sort it with EBCDIC because the string has to go in mainframe. The string I will sort ...
4
votes
2answers
9k views

Java: PriorityQueue returning incorrect ordering from custom comparator? [duplicate]

I've written a custom comparator to compare my node classes, but the java priority queue is not returning my items in the correct order.Here is my comparator:public int compare(Node n1, Node n2){...
5
votes
2answers
570 views

A Mechanism for having different equals (physical equals and logical equals) on objects in Collection

Is there any Equalator mechanism like Comparator so I can have different equals for coparing lists?EDIT: My goal is to differentiate between current list1.equals(list2) which checks if its a shallow ...
2
votes
2answers
7k views

Trouble setting a column comparator to a JTable

In another thread I found this comparator (bottom of post) for sorting JTable columns that could be composed of integers, strings, or both. I cannot figure out how to apply it to my JTable. My table ...

153050per page
angop.ao, elkhabar.com, noa.al, afghanpaper.com, bbc.com, time.com, cdc.gov, nih.gov, xnxx.com, github.com,