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.
2,766
questions
0
votes
1
answer
37
views
One list acts as a template to sort another list
Lets say there are two lists:
List<Integer> listA = Arrays.asList(1,2,3,4,5,6,7,6,5,4,3,2,1,0);
This list is a template for sorting another listB.
List<Integer> listB = Arrays.asList(0,106,...
0
votes
1
answer
92
views
Reference: Invariant for comparators in collections
Consider the following Java example:
int[] a = new int[]{1, 2};
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(Comparator.comparingInt(i -> a[i]));
pq.add(0);
pq.add(1);
a[1] = ...
-1
votes
1
answer
91
views
Java Comparison issue - Comparison method violates its general contract [duplicate]
I am trying to do a sorting of some number. I am getting a "java.lang.IllegalArgumentException: Comparison method violates its general contract!" Exception when I execute the following code.
...
-3
votes
0
answers
33
views
How to sort a list of objects by three fields of different sorting priorities? [duplicate]
I'm not super familiar with sorting in Java and I have a situation where, let's say I have a list of Member objects that contain various fields (memNum, accountAge, points). The constructor for ...
0
votes
1
answer
59
views
Java Comparator, comparing two doubles:
I use Java 17. Here is my code:
public static class SortByPercentLike implements VideoSorterInterface {
// define Lambda Function
Comparator<Video> videoPercentLikeComparator ...
1
vote
1
answer
81
views
ExoPlayer TrackSelectionDialog comparator not working
I am printing video tracks to user in "height" + "p" format.
By default TrackSelectionDialog printing them let's say in random order. I want to reorder them from min to max.
So I ...
0
votes
1
answer
65
views
How to use a customized comparator to define the innermost map of a nested map in Java?
I have a class Range and a comparator in Java:
class Range{
int start;
int end;
}
class RangeComparator implements Comparator<Range> {
@Override
public int compare(Range range1, ...
-2
votes
2
answers
85
views
How to compare two different generic instantiations of a class in Java?
MRE because well, assignment... sigh
This is the problem I'm stuck on:
Consider the following class:
class MyClass<T extends Comparable<T>> implements Comparable<MyClass<T>> {
...
0
votes
1
answer
61
views
How do I sort a tree map using a comparator that uses both key and value
So I have this class where I'm trying to initialize a SortedMap using a Comparator I created in another class (separate files)
Why is this part not working?
Comparator<Map.Entry<Country, Pair<...
2
votes
5
answers
154
views
Return the most recent date after comparing dates from array list in Java
How do I return the most recent date after comparing all the elements in the Array List? The expectation is to return 2023-01-03T02:00:00.800Z value as it is the most recent date in the list out of ...
0
votes
1
answer
52
views
Using Comparator.nullsFirst not working with reverse()
I am trying to sort Car by three values: first by type, then within the "type" bucket I want to sort those by price (lowest to highest), then if there are any that have the same price, I ...
0
votes
0
answers
20
views
python difflib.context_diff doesnt show all the elements
I'm trying to compare two .txt files in order to observe the changes have been done before. these files contains of list informations, you can see them below. If last 4 elements are exactly same, then ...
0
votes
3
answers
88
views
Understand how sorting with compare works for an ArrayList in java
I want to understand how the following comparator gives me results in ascending order:
Comparator<Integer> ints = (i1, i2) -> i1 - i2;
How does providing i1-i2 as the implementation give me ...
0
votes
1
answer
64
views
C++ map with custom comparator is not inserting all elements
I have the following code:
enum Type {
OUTPUT = 1,
INPUT = 2,
INOUT = 3
};
std::vector<int> data = {INPUT, INOUT, OUTPUT, INPUT, OUTPUT, INPUT}
My goal is to store information into a std:...
0
votes
2
answers
41
views
How to check for null before comparing by linked object key using Comparator.comparing in java
Comparator.comparing(ProjectVo::getCategory, Comparator.comparing(ProjectCategoryVo::getName))
However category can be null and hence this is throwing exception when sorted
How can i apply null ...
1
vote
1
answer
42
views
How to write custom comparator for std::set<std::pair<int,int>> where first element of pair must be unique
I am having trouble writing a strict weak ordering comparator for std::set<std::pair<int,int>> such that the first element of an inserted pair must be unique in the set, and the second ...
1
vote
1
answer
55
views
How can I initialize a std::map with opposite signature coordinate keys?
For some background information, I am trying to create a quick quadtree generation algorithm using a dictionary lookup. The basic concept involves mapping coordinates to quadtree nodes via binary ...
0
votes
0
answers
28
views
Ignore specific node within array when the element inside the node has a specific value while comparing two JSON in Java
I am trying to compare two JSON structures using Custom comparator of JSONAssert package. For example,
Data1:
{
"name": "John",
"details": {
"age": 30,
...
0
votes
0
answers
70
views
Java data structure that sorts and groups by Comparator
Is there a Java data structure that will sort and group by a provided Comparator instance?
Here is an example of what I am trying to achieve:
Input: [1, 2, 1, 3, 4, 4, 5, 3]
Output: [[1,1], [2], [3,3],...
1
vote
4
answers
151
views
Python: How to sort a list of custom objects by multiple attributes by different order?
For example, if I have a Person class
class Person:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
def __repr__(self) -> str:
return f&...
1
vote
2
answers
69
views
Java Comparator.Comparing().reversed() won't accept BigDecimal Constructor issue
I'm working on a problem where you are given a String[] containing numbers that are all formatted differently - e.g. "9", "-100", "56.6", "0.12", ".12"...
0
votes
0
answers
36
views
Kryo - Serialization of TreeMap with a Comparator - InaccessibleObjectException: Unable to make field private final java.util.Comparator
I'm using Kryo 5.2 to serialize the following TreeMap with Comparator:
public class Library {
NavigableMap<Book, String> books = new TreeMap(Book.getComparator());
}
@Getter
@Setter
class ...
1
vote
2
answers
112
views
Check if Collection of DTOs sorted by a given field
I have to write tests for a pagination and sorting GET ALL endpoint that I have. The following is the simple DTO that I am working with:
public class TransactionDto {
private Long id;
private Long ...
0
votes
0
answers
39
views
Sorting a list of objects by two different criteria in Kotlin
I'm working on a Kotlin application where I have the following class:
data class Schedule(
val id: Int,
val date: LocalDate,
val examCodes: List<String>
)
I have a List and need to ...
0
votes
1
answer
64
views
Comparator.naturalOrder() giving compiler error when implementing in class
When trying to implement the no-arg constructor for this class the compiler is giving me the following error:
Type mismatch: cannot convert from Comparator<Comparable<? super Comparable<? ...
0
votes
1
answer
59
views
Excessive Invocation of Copy Constructor for Custom Comparator Class in C++ Priority Queue
I had declared a priority_queue with custom comparator having a vector property in it. Below is the full code for it:
CODE
#include <bits/stdc++.h>
using namespace std;
class Compare
{
private:...
0
votes
1
answer
31
views
Sorting in java using lambda Expression
class Solution {
public int[] Sort(int[] nums) {
int[] arr = {1, 2, 3, 4, 5};
Arrays.sort(arr, (a, b) -> (a+""+b).compareTo((b+""+a)));//this part is showing ...
-1
votes
2
answers
60
views
JAVA Collections Modified Sorting
List<Integer> list = new ArrayList<>();
for(int i = 0 ; i <= 8 ; i ++){
list.add(i+1);
}
Collections.sort(list,(a, b)-> (a%b==0) ? 1 : (a%b==1) ? -1 : 0 );
list.forEach(System.out::...
0
votes
1
answer
49
views
Why is this lambda expression not working for defining this comparator?
I want to create a min-heap where the elements are pairs of integers and I want the heap to compare the first number in the pair. I am defining it like so:
PriorityQueue<List<Integer>> ...
1
vote
1
answer
28
views
I getting an error variable driver of type Object in Comparator.comparingDouble( ) method [duplicate]
I wanted to Match the rider with the nearest available drivers. For that I am using Comparator.comparingDouble() method.
private List<Driver> findNearbyDrivers(Rider rider) {
List<...
2
votes
3
answers
63
views
Custom ordering using Java Comparator - Retain the position for objects with certain value
I am trying to implement a custom comparator that sorts a list of objects in descending order, but while doing so, it ignores when the object has a specific value (-1 in my case). Thus, the objects ...
0
votes
2
answers
48
views
Java sorting with lambda function
Can someone please convert this function into lambda function... I am having some trouble in typecasting I guess. Help please
Arrays.sort(arr, new Comparator<Item>() {
@Override
public ...
1
vote
1
answer
163
views
Java Comparator.nullsLast and Comparator.nullsFirst not working as expected
I have the following method, which throws NPE in sort() when I am trying to sort by a field which is null in the list :
private List<MobileSearch> sortAscAndDesc(final MobilesPostResponse ...
1
vote
2
answers
40
views
Sorting an array of alphanumeric strings
I want to sort a list of names(not precisely names but alphanumeric strings) such that all names that start with a digit go to end of list and are sorted individually. While all names that start with ...
0
votes
1
answer
63
views
java - Max heap property not obeyed by PriorityQueue
I was trying out the problem Top K Frequent Elements and I am not asking for how its implemented but what is going wrong in my implementation.
My implementation idea:
Declare a HashMap to count the ...
0
votes
0
answers
43
views
Jodatime - Comparison method violates its general contract
assume the following java method:
private Collection<TimeDTO> sortTimes(Choice choice) {
final List<TimeDTO> times = new ArrayList<>(timeCache.getAll(choice));
Collections....
0
votes
0
answers
40
views
Implementing comparator in constructor when PriorityQueue is nested
I want to make the following:
ArrayList of PriorityQueue of Integer[](
ArrayList<PrirorityQueue<Integer[]>> )
But I am unable to implement Comparator in the constructor area.
ArrayList&...
1
vote
1
answer
49
views
How does this algorithm using Array.sort(T[] a, Comparator<? super T> c) sort n x 2 matrixes?
Arrays.sort(nx2Matrix, (a, b) -> {
if (a[0] == b[0]) return a[1] - b[1];
else return a[0] - b[0];
});
This sorts n x 2 matrixes to be in ascending order primarily by the first index, then ...
1
vote
3
answers
386
views
How to use custom comparator in Rust?
I am trying to sort vector with help of custom comparator. What is the proper way to do it in Rust?
My code
use std::cmp::Ordering;
fn main() {
let mut v = vec![0, -4, 1, 2, 3];
v.sort_by(|a, ...
0
votes
1
answer
39
views
Java - Is it possible to create a Comparator factory with an argument which changes the compare method?
I have a class VectorClock which extends ArrayList<Integer>. I want to sort the elements, but these only have a partial order. A vector clock is greater than another only if all the elements are ...
0
votes
0
answers
30
views
Using Tree Set in java with user defined class [duplicate]
I am trying to add elements of pair in TreeSet, but somehow it is using the comparator to decide which value to be inserted.
class pair{
int i;
int j;
int w;
pair(int i,int j,int w){
...
0
votes
1
answer
47
views
How to sort an array of key values alphabetically by the value in a stream? (Java)
I'm trying to learn more about comparators and streams and I was wondering the best solution to sort an array of objects with key values, sorting alphabetically by the value. Any help is hugely ...
1
vote
1
answer
195
views
Cannot read property of undefined in comparator function
I have a quicksort algoritm (Hoare Partition Scheme) for objects of my class and three comparators.
class Participant {
login;
fine;
solved;
}
/*This function should convert array of ...
1
vote
1
answer
78
views
How to sort List<Object> in a Map<String, Object> in Java?
I have two maps, Map<String,Object> which looks like:
Map<String, Object> map1 = {
taxRate={rateType=EXCLUSIVE, rate=0.07},
taxAmount={currencyCode=USD, amount=7.0},
...
0
votes
1
answer
528
views
priority_queue of pairs of integers in c++ where first elements: descending order, the second elements: ascending order if first elements are equal
I am trying to build a priority queue of pairs of integers in C++ with a custom comparator, where the first elements will be sorted in descending order, but if the first elements of the two pairs are ...
1
vote
2
answers
155
views
why is my comparator function not working?
I have an array with elements as [0, 1, 0, 3, 12]. I want to shift all the zeros to the end of it while maintaining the relative order of the non-zero elements. After shifting the array should look ...
1
vote
1
answer
79
views
How to address a Comparator of a class in external generic method?
I'm looking into how to use comparators to perform comparisons based on different fields.
So I created a class Event, which contains two Comparators.
class Event {
int x, y;
boolean isLeft;
...
0
votes
0
answers
19
views
Python class with multi custom compare functions used in priorityqueues
I have a class person and it has three custom compare functions (compare_by_name / age / height), and i need three priorityQueue(Or Heapq) to save objects seperately using different compare functions? ...
0
votes
0
answers
111
views
Compare Two Large JSON array
I have two directories "A" and "B", each directory contains textfiles containing jsonarray of jsonobjects.
Need to compare jsonobjects in directory a with b and figure out which ...
0
votes
1
answer
107
views
Why does C++ comparator behaves inversly in priority_queue and sort()? [duplicate]
Edit: Yes I have made a mistake defining the comparator. I have changed the operator to <. The behavior is now defined and does not change.
I defined a simple comparator class
class MyCompare {
...