sort a list of #Sortable objects in descending order - sorting

I have a class
#Sortable(includes = ['date'])
class Item {
// other fields not relevant to this question
Date date
}
If I sort a List of these objects it will sort them in ascending order based on the date field. Is there a way to sort them in descending order instead? I know I could just call reverse() on the result of the ascending sort, but this seems a bit inefficient

Here are a couple of ways:
def items = [
new Item(date: new Date(40000)),
new Item(date: new Date(1000)),
new Item(date: new Date(200000)),
new Item(date: new Date(00100)),
]
items.sort { a, b -> b <=> a }
items.sort(true, Collections.reverseOrder())

Related

How to sort string with numbers in it numerically?

So I am getting some json data and putting it inside of a Mutable List. I have a class with id, listId, and name inside of it. Im trying to sort the output of the list by listId which are just integers and then also the name which has a format of "Item 123". Im doing the following
val sortedList = data.sortedWith(compareBy({ it.listId }, { it.name }))
This sorts the listId correctly but the names is sorted alphabetically so the numbers go 1, 13, 2, 3. How am I able to sort both the categories but make the "name" also be sorted numerically?
I think
val sortedList = data.sortedWith(compareBy(
{ it.listId },
{ it.name.substring(0, it.name.indexOf(' ')) },
{ it.name.substring(it.name.indexOf(' ') + 1).toInt() }
))
will work but it is not computationally efficient because it will call String.indexOf() many times.
If you have a very long list, you should consider making another list whose each item has String and Int names.

How to use sortedWith() in kotlin?

I am trying to sort that simple list of users by "created". What am I doing wrong?
val user1 = User("2019-01-01 17:42:34")
val user2 = User("2019-01-02 17:42:34")
val user3 = User("2019-01-03 17:42:34")
val list = listOf(user2, user3, user1)
list.sortedWith(compareBy {
LocalDateTime.parse(
it.created,
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
)
})
data class User(val created: String = "")
Your code works. The problem here is that sortedWith returns a new list with the results of the sorting! Check the documentation:
Returns a list of all elements sorted according to the specified [comparator].
The sort is stable. It means that equal elements preserve their order relative to each other after sorting.
So if you want to sort the collection itself you need to use a MutableList and sortWith:
val list = mutableListOf(User("2019-01-01 17:42:34"), User("2019-01-02 17:42:34"), User("2019-01-03 17:42:34"))
list.sortWith(compareBy {
LocalDateTime.parse(
it.created,
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
})
sortedWith function returns a new list with sorted elements without modifying the original collection. You probably want to use sortWith function of MutableList that sorts the original collection.

Sort list of list of objects

I want to sort the list of elements based on the list of value inside it.
class Response {
List<Group> groupList;
Integer sequenceNo;
}
class Group {
Integer discount;
List<String> rates;
}
Looking to sort ascending List<Response> according to the discount. Basically, groupList will have single element most of the time, but structure is defined as list. Is it possible with java8 to sort the responseList with group having highest discount.
Try the following:
List<Response> sortedResponse = responses.stream()
.sorted(comparingInt(response -> response.groupList.get(0).discount))
.collect(toList());

How to sort a list of strings by using the order of the items in another list?

I want to sort a list of strings (with possibly duplicate entries) by using as ordering reference the order of the entries in another list. So, the following list is the list I want to sort
List<String> list = ['apple','pear','apple','x','x','orange','x','pear'];
And the list that specifies the order is
List<String> order = ['orange','apple','x','pear'];
And the output should be
List<String> result = ['orange','apple','apple','x','x','x','pear','pear'];
Is there a clean way of doing this?
I don't understand if I can use list's sort and compare with the following problem. I tried using map, iterable, intersection, etc.
There might be a more efficient way but at least you get the desired result:
main() {
List<String> list = ['apple','pear','apple','x','x','orange','x','pear'];
List<String> order = ['orange','apple','x','pear'];
list.sort((a, b) => order.indexOf(a).compareTo(order.indexOf(b)));
print(list);
}
Try it on DartPad
The closure passed to list.sort(...) is a custom comparer which instead of comparing the passed item, compares their position in order and returns the result.
Using a map for better lookup performance:
main() {
List<String> list = ['apple','pear','apple','x','x','orange','x','pear'];
List<String> orderList = ['orange','apple','x','pear'];
Map<String,int> order = new Map.fromIterable(
orderList, key: (key) => key, value: (key) => orderList.indexOf(key));
list.sort((a, b) => order[a].compareTo(order[b]));
print(list);
}
Try it on DartPad

How to get values after dictionary sorting by values with linq

I've a dictionary, which i sorted by value with linq, how can i get those sorted value from the sorted result i get
that's what i did so far
Dictionary<char, int> lettersAcurr = new Dictionary<char, int>();//sort by int value
var sortedDict = (from entry in lettersAcurr orderby entry.Value descending select entry);
during the debug i can see that sortedDic has a KeyValuePar, but i cant accesses to it
thanks for help
sortedDict is IEnumerable<KeyValuePair<char, int>> iterate it
Just iterate over it.
foreach (var kv in sortedDict)
{
var value = kv.Value;
...
}
If you just want the char values you could modify your query as:
var sortedDict = (from entry in lettersAcurr orderby entry.Value descending select entry.Key);
which will give you a result of IEnumerable<char>
If you want it in a dictionary again you might be tempted to
var q = (from entry in lettersAcurr orderby entry.Value descending select entry.Key).ToDictionary(x => x);
but do bare in mind that the dictionary will not be sorted, since the Dictionary(Of T) will not maintain the sorted order.

Resources