Skip to content

Tag: comparator

How to write custom comparator in java?

I want to store key-value pairs in TreeMap and sort the entries based on the value of key as per the following logic: “type” (case insensitive) key should be at first. the key start with “metadata” (case insensitive) should be at last in ascending order rest of the keys(case insensitiv…

Sort List of string arrays by first element

I want to sort a list of string arrays by first element in each array element of same list, in reverse order, so 2, 1, 0 Here’s what i tried so far: The problem is that at sorted line i have an error highlighted, saying: “sorted(java.util.List, java.util.Comparator Answer Stream.sorted() takes a c…

understanding comparator in Collections.max

Can somebody please explain what the following lines of code mean?. I had a hard time understanding the Comparator part.I tried googling but all of them were too complex for me to understand. Could somebody please explain it in simpler way? Answer The max method returns the element that is considered the &#82…

TreeSet constructor with Comparator parameter

In Java’s documentation for its class TreeSet one of the constructors is shown to have the following header: Can someone help explain why there is a constructor for TreeSet which takes a comparator object as its argument? I have no clue why this is done. Answer The elements in a TreeSet are kept sorted. If yo…

how to test Comparator at junit test

I need to test this method – compare(). Can You get advice? How better I can do this(all part if, else-if, else). After this recomendations – we have next picture (Thank YOU guys a lot!): All is normal testing now. Answer Just instantiate your comparator class and pass in objects: