按第一元素反向,第二元素常规对元组进行排序 [英] Sort tuples by first element reverse, second element regular
问题描述
我有一个(Boolean, Int, String)
形式的元组.
我想定义以以下顺序对元组进行排序的排序:
I want to define Ordering which sorts the tuples in the following order:
-
布尔型-逆序
Boolean - reverse order
Int-逆序
字符串-常规订单
示例:
对于元组:Array((false, 8, "zz"), (false,3, "bb"), (true, 5, "cc"),(false, 3,"dd"))
.
排序应为:
(true, 5, "cc")
(false, 8,"zz")
(false, 3, "bb")
(false, 3, "dd")
我找不到定义一些反向排序和一些常规排序的方法.
I couldn't find a way to define some of the ordering reverse and some regular.
推荐答案
在此特定情况下,直接的解决方案是在元组上使用sortBy
,并对其进行动态修改以反转"第一个和第二个元素,以便最后,顺序颠倒了:
The straight forward solution in this specific case is to use sortBy
on the tuples, modified on the fly to "invert" the first and second elements so that in the end the ordering is reversed:
val a = Array((false, 8, "zz"), (false,3, "bb"), (true, 5, "cc"),(false, 3,"dd"))
a.sortBy{ case (x,y,z) => (!x, -y, z) }
对于无法轻松反转"值的情况(例如,这是一个引用对象,并且对它们具有不透明的顺序),可以改用
sorted
并显式传递一个构造为反转第一个和第二个元素的顺序的顺序(您可以使用Ordering.reverse
颠倒顺序):
For cases when you cannot easily "invert" a value (say that this is a reference object and you've got an opaque ordering on them), you can instead use
sorted
and explicitly pass an ordering that is constructed to invert the order on the first and second elements (you can use Ordering.reverse
to reverse an ordering):
val myOrdering: Ordering[(Boolean, Int, String)] = Ordering.Tuple3(Ordering.Boolean.reverse, Ordering.Int.reverse, Ordering.String)
a.sorted(myOrdering)
这篇关于按第一元素反向,第二元素常规对元组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!