Using sortBy on multiple elements in a List of Nested Tuples in Scala
Clash Royale CLAN TAG#URR8PPP
Using sortBy on multiple elements in a List of Nested Tuples in Scala
Given the following data type [((String, String), Double)]
in Scala how would I used the sortBy function to sortby the First String then the second String? There are some answers for sorting on multiple values but what about in the case below?
[((String, String), Double)]
var test =
List((("C","c"),4.3), (("A","c"),1.4), (("C","d"),80.1))
test.sortBy(???).foreach(println)
Output should provide following
(("A","c"),1.4),
(("C","c"),4.3),
(("C","d"),80.1)
2 Answers
2
Since the elements within each tuple ((s1, s2), d)
are already in the order (from left to right) you want for the sorting, you can simply do this:
((s1, s2), d)
test.sortBy(identity)
// List[((String, String), Double)] = List(((A,c),1.4), ((C,d),80.1), ((D,c),4.3))
Or, just use sorted
:
sorted
test.sorted
// List[((String, String), Double)] = List(((A,c),1.4), ((C,d),80.1), ((D,c),4.3))
You can do that sorting by a tuple where every element, from left to right is more relevant.
var test = List((("D","c"),4.3), (("A","c"),1.4), (("C","d"),80.1))
test.sortBy case ((a,b),c) => (a,b,c) .foreach(println)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.