DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Top Six React Development Tools
  • RAML vs. OAS: Which Is the Best API Specification for Your Project?
  • Which Is Better for IoT: Azure RTOS or FreeRTOS?
  • Integration Testing Tutorial: A Comprehensive Guide With Examples And Best Practices

Trending

  • Top Six React Development Tools
  • RAML vs. OAS: Which Is the Best API Specification for Your Project?
  • Which Is Better for IoT: Azure RTOS or FreeRTOS?
  • Integration Testing Tutorial: A Comprehensive Guide With Examples And Best Practices
  1. DZone
  2. Data Engineering
  3. Data
  4. Custom Ordering Scala TreeMap

Custom Ordering Scala TreeMap

Peter Pilgrim user avatar by
Peter Pilgrim
CORE ·
Jul. 23, 12 · Interview
Like (0)
Save
Tweet
Share
10.70K Views

Join the DZone community and get the full member experience.

Join For Free

How do you get custom ordering in a Scala TreeMap?

Well this puzzled me for a while. The answer lies in the world of implicits and receiver type converters.

In a nut shell, a scala.collection.immutable.TreeMap is a SortedMap. If you look at the documentation for TreeMap, you will see it takes an Ordering[T] as an implicit argument.

Normally when you declare a TreeMap, say inline, it will use the default Ordering object like so:-

scala> val dtm = TreeMap( "a" -> 1, "bc" -> 2, "def" -> 3 )
dtm: scala.collection.immutable.TreeMap1 = Map(a -> 1, bc -> 2, def -> 3)

If you want to change the ordering of the keys, for example, instead of the ascending order by String content, into, say, a descending order of strings length then you need an Ordering type.

scala> object VarNameOrdering extends Ordering[String] {
         def compare(a:String, b:String) = b.length compare a.length
       }
defined module VarNameOrdering

Now you can use the second argument list in an explicit fashion like this:

scala> val tm1 = TreeMap( "a" -> 1, "bc" -> 2, "def" -> 3 )( VarNameOrdering )
tm: scala.collection.immutable.TreeMap1 = Map(def -> 3, bc -> 2, a -> 1)

We pass the object to the TreeMap, which is rather similiar to a Java Collection Comparator object without the boilerplate instantiation. The keys of the TreeMap are now ordered by String lengths. We add more elements and the map will stay ordered.

val tm2 = tm1 + ( "food" -> 4 )
cala.collection.immutable.TreeMap1 = Map(food -> 4, def -> 3, bc -> 2, a -> 1)

However, a word of caution, one needs to be careful and remember that maps are usually implemented as hashes.

scala> val tm3 = tm2 + ( "z" -> 5 )
tm3: scala.collection.immutable.TreeMap1 = Map(food -> 4, def -> 3, bc -> 2, z -> 5)

Surprised? You should be.

Another way to sort a map is just to get access to the keys and sort.

scala> dtm.keys.toList.sortWith ( _.length > _.length )
res3: List1 = List(salad, def, bc, a)
 
scala> dtm.keys.toList.sortWith ( _.length > _.length ).map( k => ( dtm.get(k).get ))
res4: List[Int] = List(10, 3, 2, 1)
 
scala> dtm.keys.toList.sortWith ( _.length > _.length ).map( k => ( k, dtm.get(k).get ))
res5: List[(java.lang.String, Int)] = List((salad,10), (def,3), (bc,2), (a,1))

This may well be a better solution, as you have not lost a key in flight! Considering how data is going to be stored is a major decision that needs to be taken early. You can always decide how to write projection of that data much later.

Finally, it is interesting to see the parallels between Java and Scala

scala> dtm.keys
res6: Iterable1 = Set(a, bc, def, salad)
 
scala> dtm.keys.toList
res7: List1 = List(a, bc, def, salad)

PS: I can safely say I have used Scala professionally today in financial enterprise.

 

 

 

 

 

 

 

Data structure Scala (programming language)

Published at DZone with permission of Peter Pilgrim, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Top Six React Development Tools
  • RAML vs. OAS: Which Is the Best API Specification for Your Project?
  • Which Is Better for IoT: Azure RTOS or FreeRTOS?
  • Integration Testing Tutorial: A Comprehensive Guide With Examples And Best Practices

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: