0

I'm trying to sort a Map by value using Scala but no luck any help will be appreciable. "null value can be any order"

Input:

Map(dkd-> 2, dtes-> 3,test-> 4, dstl-> null,tsst-> null, tetd-> null ,est1-> 1)

Output

Map(est1-> 1, dkd-> 2, dtes-> 3, test-> 4, tsst-> null, dstl-> null, tetd-> null)

or

Map(est1-> 1, dkd-> 2, dtes-> 3, test-> 4, dstl-> null, tetd-> null, tsst-> null)

or

Map(est1-> 1, dkd-> 2, dtes-> 3, test-> 4, tetd-> null, dstl-> null, tsst-> null)

2
  • Maps are not sorted, especially not by value. Why do you care about the order? Is for printing? Commented Jul 2, 2020 at 20:16
  • 1
    If you need to sort a map, you are using the wrong structure, because maps are not meant to be accessed by order, they are supposed to be accessed by key Commented Jul 2, 2020 at 20:23

1 Answer 1

3

A Map, by definition, has no order, but a List does.

Map("dkd"-> 2
  , "dstl"-> null
  , "test"-> 4
  , "tsst"-> null
  , "dtes"-> 3
  , "tetd"-> null
  , "est1"-> 1
  ).toList.sortBy{
    case (_:String,i:Int) => i
    case _ => Int.MaxValue
  }
//res0: List[(String, Any)] = 
// List((est1,1)
//    , (dkd,2)
//    , (dtes,3)
//    , (test,4)
//    , (tsst,null)
//    , (dstl,null)
//    , (tetd,null))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.