|By York Davis||
|August 5, 2004 12:00 AM EDT||
Those familiar with the java.util.Comparator interface of the Java API realize its capabilities for sorting a collection of objects based on an attribute of the objects in the collection. This works well when there is only a single field in which sorting is required. When more complex sorting is necessary, the limitations of sorting on a single field become obvious. What about the situation in which a user desires the functionality to sort selectively on any field in object collection? This article describes an implementation of the Comparator interface that along with the reflection API allows an object to be sorted dynamically on any of its publicly accessible fields.
Let's describe the problem a bit more specifically. A collection of employee Transfer Objects (EmployeeTO class) exists. (For a description of the Transfer Object design pattern consult a software design pattern book.) Each EmployeeTO in the collection is a data container object for a single employee's information. For this example, our simplified EmployeeTO object contains only three pieces of data - employee ID, last name, and salary.
A Human Resources application also exists that uses this collection to display a list of all employee data to HR application users. The users of this system have the following requirements:
- Allow sorting on any field on the report
- Allow control of the sort order
Before delving into our dynamic sorting solution that allows sorting on any attribute, let's first look at a simple solution that supports sorting on a single attribute only. This will demonstrate the basic behaviors of Comparator and from this we'll be able to glean the improvements we wish to make. This solution utilizes the more common use of the Comparator interface. There are two classes required to implement this.
EmployeeTO - Simple Version
First, our EmployeeTO can be made sortable by implementing the Comparator interface as shown in Listing 1. In addition to the getters and setters for ID, last name, and salary, EmployeeTO must implement the compare() and equals() methods in order to meet the Comparator's requirements. These methods define how EmployeeTO is to be sorted. The compare() method takes two parameters, both of type Object. Note that compare() returns an int. This return value tells the sort engine the collating sequence equality of two attribute values from each of the object parameters passed to compare(), respectively. We need to write the code that performs this evaluation. The first step in compare() is to cast the two parameters' objects to EmployeeTO objects and extract the employee IDs by calling the getId() method on each object in turn. Now we can compare the values. There are really only three possible outcomes that can result from this comparison. Table 1 describes the results based on these outcomes.
The other method we must code is the equals() method. Although this method is not used for sorting, it must be implemented in order to meet the contract of the Comparator interface.
Sorting the Collection - Simple Version
The SimpleTest class in Listing 2 adds three EmployeeTO objects to a List, then performs a sort on that Collection. (Listings 2-5 can be downloaded from www.sys-con.com/java/sourcec.cfm.) Line 30 of SimpleTest calls the static sort() method of the Collections class to actually perform the sort as follows.
Collections.sort(elements, new EmployeeTO());
The first parameter passed to sort() is the collection object we wish to have sorted. The second parameter is an object of type Comparator that contains the customized sorting logic - in this case EmployeeTO, which implements the Comparator interface. We certainly could have passed any instance of EmployeeTO as the second parameter to the above method call. However, instead of reusing one of the three values initially added to the collection, I chose to pass a new instance of the class for purposes of clarity.
A quick note on encapsulation and responsibility assigning seems to be in order here. In this case, it makes sense to encapsulate the specific compare() method sorting logic within EmployeeTO. With the information we have thus far, EmployeeTO is the only class that requires the knowledge of how it should be sorted. Later, as a dynamic sorting solution is provided, we'll see this sorting logic moved out of the Transfer Object class as the sorting logic becomes less specific to any one particular Transfer Object implementation.
This implementation will run but falls short when it comes to meeting the user's requirements. Remember, we need to be able to sort on any one of the three fields in EmployeeTO based on a user's choice. And let's not forget about the ability to control the sort order.
Let's think about the options that are available to improve what we have and meet the requirements. One option is to code nested if/else statements in our compare() method to allow for sorting on any field in the object based on some field name parameter passed to EmployeeTO. The problem with this solution is that it's difficult to maintain and the code could get rather lengthy as well. If new fields are added to EmployeeTO, we must update compare() appropriately.
What we would really like to do is invoke any given getter method of our Transfer Object at runtime without having to specifically hard code each possible method call in the compare() method. If we could do this, we could use the results of those method calls to dynamically determine equality. In addition, it would be desirable if this dynamic sorting could be reused for any Transfer Object. The good news is that this functionality can be achieved by leveraging the reflection API and the flexibility of the Collections.sort() method.
The java.lang.reflect.Method class provides the ability to invoke a method of a given object based on the value of a string. For example, using a string containing the value "getId", the method getId() of EmployeeTO can be dynamically invoked at runtime. This string value can then be changed as we wish to cause any of the methods of EmployeeTO to be called.
The reflection API provides a variety of interesting features including the ability to pass parameters to methods and the ability to determine method return types. (For a complete list of these capabilities, consult the Java API Javadoc.) We will need the latter capability as the three getter methods of EmployeeTO return different types and it will thus be necessary to be aware of which type we have when doing the comparison in the compare() method. For example, we'll need to code a different sort of equality test on an int return value as opposed to a string.
A dynamic solution will also need to take advantage of the flexibility of the Collections.sort() method. Recall that in our simple sorting solution we passed an instance of an object that implemented the Comparator interface as the second parameter to Collections.sort(). In that case, it was the EmployeeTO object that contained the sorting logic. This worked great for what we needed it to do. Now, however, we want something a bit more sophisticated and flexible. What if we were to create a class that implemented Comparator, which was separate from each Transfer Object? In it we could place our dynamic sorting code and simply pass an instance of this new class as the second parameter to Collections.sort().
Doing this would cause several desirable results. First, we'll have completely decoupled any sorting logic from our Transfer Objects. This is highly desirable as it decreases not only the size of each Transfer Object by essentially eliminating the need for sorting code, but also removes the need for coding individual field comparison logic. Second, we'll have created a reusable utility class that can be used in many different situations where sorting is required. While reusability is not a specifically stated user requirement for our design, it is certainly desirable.
Figure 1 is a UML diagram (with attribute and method details omitted) that shows how the components of both the simple and the dynamic sorting solutions fit together. Really, the only portion that has changed since our simple solution is where the Comparator interface gets implemented. In the first example, EmployeeTO implemented Comparator directly. Now DynamicComparator implements Comparator and contains an intelligent implementation of the compare() method that can be used by any class that requires a collection of objects to be sorted.
Listing 3 shows the completed code listing for DynamicComparator. There are a number of interesting things about this class. First, note the class signature. The class implements two interfaces - Comparator and Serializable. Comparator should come as no surprise since that interface is the essence of the sorting capabilities we desire. Also, although not a requirement, the API docs recommend that any class implementing Comparator implement Serializable as well.
Second, look at the static sort() method. Classes wishing to utilize DynamicComparator will call this method rather than Collections.sort(). I've decided to make sort() static to mimic the Collections.sort() method. Although the DynamicComparator.sort() method is called statically, internally DynamicComparator creates an instance of itself. This is necessary in order for it to provide access to the nonstatic compare() and equals() methods of the Comparator interface that it supports. Next note how this method takes three parameters. The first is the collection object to be sorted. The second is a string that defines the field of each object in the collection on which sorting should be performed. The last parameter is a Boolean specifying the sort order. These three parameters are used as arguments to create a new instance of DynamicComparator that is the second parameter passed to the Collections.sort() method.
Third, take a look at the compare() method. This is where the reflection code really kicks in. One of the first things we need to obtain is a reference to a method object at line 43. We'll use this reference to call methods dynamically. This task is done using the getMethod() helper method, which obtains this value via reflection. Next, we need to determine the return type of the methods we are about to call. Remember that we will need to compare the attribute values of the two objects passed into compare(). If the return type is an int, for instance, we'll certainly have to write different code to do the comparison than if the return type is a string. Once we have the return type, we examine it and, based on its value, dynamically perform the actual method invocation and resulting comparison of the two values.
Note that currently there are three separate "if" test blocks - one each for string, int, and double. The implementation requires comparison logic for any method return type we expect to encounter. For the range of return types in our EmployeeTO example, these three are sufficient. However, additional code would need to be added to DynamicComparator if comparisons of other types are required - short, java.util.Date, java.math.BigDecimal, etc. Coding for each specific return type here is unavoidable as there is no way to dynamically cast Java objects. Similarly, Java-supplied nonobject data types like int, long, and double use entirely different comparison operators than do first-class object types like String or Date.
There are some other important points about this code. First, DynamicComparator fully supports null values. If either or both of the arguments passed to compare() are null, this method knows how to handle the situation accordingly. Second, look at each return statement within compare(). Remember the requirement that the user be able to control not only the sort field but also the sort order? This code supports the latter by essentially reversing the default sort order with a call to getSortOrder(). This is done if the user has decided to sort the result in descending order based on the Boolean value passed into the constructor from the sort() method. Third, the constructMethodName() method converts a Transfer Object attribute name string into a method name by prepending a "get" string and capitalizing the first character of the passed value. For instance, constructMethodName() would convert "salary" to "getSalary".
Last, the equals() method is needed to complete the interface requirements.
EmployeeTO - Enhanced Version
Listing 4 shows the enhanced version of EmployeeTO. The most obvious change is that EmployeeTO is now even simpler than before. Now that all of the sorting logic has been moved to DynamicComparator and the class no longer implements Comparator, we don't need to implement the compare() and equals() methods.
Sorting the Collection - Dynamic Version
Listing 5 is the code for DynamicTest. The only change between this class and SimpleTest is how the sort is called. Here we pass the three parameters to DynamicComparator.sort() (Collection Object, the decapitalized attribute name, and sort ascending flag) and let the DynamicComparator do the rest.
DynamicTest could just as easily have sorted on last name by passing "lastName" or on employee ID by passing "id" as the second parameter on line 29.
Building a class such as DynamicComparator has many benefits in an application that requires robust sorting capabilities. In this design, we have created a reusable, loosely coupled API that can be used to sort a collection of objects based on getter methods. The sort field is easily configurable and also allows control over the sort order.
This design, however, is not without trade-offs. Although using the reflection API allows us to do lots of cool things, using reflection can slow performance. This is particularly true in applications using pre-1.4 versions of Java. In addition, it's possible that applications wishing to sort very large collections may find DynamicComparator too slow.
Other inadequacies of DynamicComparator might become evident as well. Although it allows sorting on any one attribute of a collection of objects in an easily configurable manner, DynamicComparator does not address the potential need to sort by multiple fields - primary and secondary field sorts like that occur automatically with the ORDER BY clause in Structured Query Language (SQL).
This article introduced a reusable implementation of the Comparator interface that utilizes Java reflection to dynamically sort a collection of objects on any one of any number of fields within that object.
If your application or framework has a need for this specific functionality, perhaps this design will fit your needs.
|Java 04/09/08 09:42:59 AM EDT|
Refer below link for code
|Doug Bell 08/26/04 04:26:21 AM EDT|
I meant to mention one other thing about the articles implementation that nobody else mentioned. The implementation and comment for the DynamicComparator.equals method illustrates confusion about the purpose of the method.
As implemented, the equals method breaks all contracts for equals, including the Comparator contract. It would be better to have left the default implementation of equals rather than override it with a method that always returns true.
The equals method is for comparing the DynamicComparator object to another object to see if two Comparators produce the same results. This would not be too difficult to properly implement by checking for equals between the method and sortAsc fields (and Comparator fields if my previous suggestion was implemented).
One final comment is that the Collection should not be passed to the DynamicComparator constructor. It is only needed by the sort method.
|Doug Bell 08/26/04 04:11:27 AM EDT|
sMyles has the right idea about how to fix the DynamicComparator class. (Some of the other comments and code suggestions missed the mark in one or more areas.) Certainly, you''d rather not have to keep modifying the DynamicComparator class to add new algorithms--this is not the correct design for "encapsulation and responsibility assignment" that the article discusses.
However, instead of sMyles suggestion for option 4, just overload sort() and the DynamicComparator constructor to accept a Comparator for comparing any two fields that don''t implement Comparable. This will also allow fields that do implement Comparable, such as String, to use alternate compare algorithms, such as compareToIgnoreCase.
|David Perelman-Hall 08/11/04 03:26:40 PM EDT|
public final class DynamicComparator implements Comparator
// Object Members
// Private Constructor
// Sort invocation starts here
// Compare for Collections.sort here
// Invoke method to gather two comparable objects
// Sort order getter
EmployeeTO e2 = new EmployeeTO();
EmployeeTO e1 = new EmployeeTO();
EmployeeTO e3 = new EmployeeTO();
DynamicComparator.sort(elements, "getLastName", true);
final Iterator li = elements.iterator();
|sMyles 08/11/04 03:14:36 PM EDT|
It is important to note that invoke() returns an Object, not a primitive.
Knowing this, compare() should do the following:
2. Perform the null comparisons on val1 and val2 (without the introduction of val1Null and val2Null) and return the appropriate value * getSortOrder(), if applicable.
3. If it turns out neither return value is null, return val1.compareTo(val2) * getSortOrder()
4 (optional). Include a special case for String objects and return val1.compareToIgnoreCase(val2) * getSortOrder(). How compare() should treat case sensitivity could be specified as a parameter to sort().
Also of note:
|Ceri 08/10/04 05:07:56 PM EDT|
Sorry, formatting seems to have been stripped from my previous message.
|Ceri 08/10/04 05:06:17 PM EDT|
The compare method needs to handle primitive types separately. All non-primitives that implement comparable can be easily grouped together into a single if block (to replace the String handling section of Listing 3):
Class interfaces = method.getReturnType().getInterfaces();
|Mike 08/10/04 12:16:23 PM EDT|
York the method "public int compare(Object o1, Object o2)" is long and makes the class look cluddered(like it needs to be refactored), especially if more fields where added requiring more test to be implemented in this method. Wouldn''t separate class implementation for each sorting type help with this, but on second thought this would lead to class proliferation. Okay in the future, would sometype of generics in 1.5.0 work here for the comparing class in addition to the usage of reflection to stream line this code.
|York 08/09/04 01:22:26 PM EDT|
Source code now available for download!
|S Opoku-Boadu 08/09/04 03:26:33 AM EDT|
Cannot locate Listings 2 - 5
|S Opoku-Boadu 08/09/04 03:25:52 AM EDT|
Cannot locate Listings 2 - 5
|Trevor Leach 08/09/04 12:38:46 AM EDT|
The listings are not in the print version either. Perhaps we''ll get emailed when they are found?
|D Polansky 08/05/04 05:41:40 PM EDT|
Where are listings 3, 4, and 5 referenced in the article?
We’re entering a new era of computing technology that many are calling the Internet of Things (IoT). Machine to machine, machine to infrastructure, machine to environment, the Internet of Everything, the Internet of Intelligent Things, intelligent systems – call it what you want, but it’s happening, and its potential is huge. IoT is comprised of smart machines interacting and communicating with other machines, objects, environments and infrastructures. As a result, huge volumes of data are being generated, and that data is being processed into useful actions that can “command and control” thi...
May. 29, 2015 02:00 PM EDT Reads: 1,146
The Internet of Things is tied together with a thin strand that is known as time. Coincidentally, at the core of nearly all data analytics is a timestamp. When working with time series data there are a few core principles that everyone should consider, especially across datasets where time is the common boundary. In his session at Internet of @ThingsExpo, Jim Scott, Director of Enterprise Strategy & Architecture at MapR Technologies, discussed single-value, geo-spatial, and log time series data. By focusing on enterprise applications and the data center, he will use OpenTSDB as an example t...
May. 29, 2015 02:00 PM EDT Reads: 6,846
All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades. With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo, June 9-11, 2015, at the Javits Center in New York City. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be
May. 29, 2015 01:15 PM EDT Reads: 3,045
Scott Jenson leads a project called The Physical Web within the Chrome team at Google. Project members are working to take the scalability and openness of the web and use it to talk to the exponentially exploding range of smart devices. Nearly every company today working on the IoT comes up with the same basic solution: use my server and you'll be fine. But if we really believe there will be trillions of these devices, that just can't scale. We need a system that is open a scalable and by using the URL as a basic building block, we open this up and get the same resilience that the web enjoys.
May. 29, 2015 01:00 PM EDT Reads: 7,501
We are reaching the end of the beginning with WebRTC, and real systems using this technology have begun to appear. One challenge that faces every WebRTC deployment (in some form or another) is identity management. For example, if you have an existing service – possibly built on a variety of different PaaS/SaaS offerings – and you want to add real-time communications you are faced with a challenge relating to user management, authentication, authorization, and validation. Service providers will want to use their existing identities, but these will have credentials already that are (hopefully) i...
May. 29, 2015 01:00 PM EDT Reads: 4,752
SYS-CON Events announced today that MetraTech, now part of Ericsson, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Ericsson is the driving force behind the Networked Society- a world leader in communications infrastructure, software and services. Some 40% of the world’s mobile traffic runs through networks Ericsson has supplied, serving more than 2.5 billion subscribers.
May. 29, 2015 01:00 PM EDT Reads: 2,446
Thanks to widespread Internet adoption and more than 10 billion connected devices around the world, companies became more excited than ever about the Internet of Things in 2014. Add in the hype around Google Glass and the Nest Thermostat, and nearly every business, including those from traditionally low-tech industries, wanted in. But despite the buzz, some very real business questions emerged – mainly, not if a device can be connected, or even when, but why? Why does connecting to the cloud create greater value for the user? Why do connected features improve the overall experience? And why do...
May. 29, 2015 12:42 PM EDT Reads: 568
SYS-CON Events announced today that O'Reilly Media has been named “Media Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York City, NY. O'Reilly Media spreads the knowledge of innovators through its books, online services, magazines, and conferences. Since 1978, O'Reilly Media has been a chronicler and catalyst of cutting-edge development, homing in on the technology trends that really matter and spurring their adoption by amplifying "faint signals" from the alpha geeks who are creating the future. An active participa...
May. 29, 2015 12:30 PM EDT Reads: 1,296
SYS-CON Events announced today that BMC will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. BMC delivers software solutions that help IT transform digital enterprises for the ultimate competitive business advantage. BMC has worked with thousands of leading companies to create and deliver powerful IT management services. From mainframe to cloud to mobile, BMC pairs high-speed digital innovation with robust IT industrialization – allowing customers to provide amazing user experiences with optimized IT per...
May. 29, 2015 12:15 PM EDT Reads: 1,596
Imagine a world where targeting, attribution, and analytics are just as intrinsic to the physical world as they currently are to display advertising. Advances in technologies and changes in consumer behavior have opened the door to a whole new category of personalized marketing experience based on direct interactions with products. The products themselves now have a voice. What will they say? Who will control it? And what does it take for brands to win in this new world? In his session at @ThingsExpo, Zack Bennett, Vice President of Customer Success at EVRYTHNG, will answer these questions a...
May. 29, 2015 12:13 PM EDT Reads: 595
The 4th International Internet of @ThingsExpo, co-located with the 17th International Cloud Expo - to be held November 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA - announces that its Call for Papers is open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
May. 29, 2015 12:00 PM EDT Reads: 2,659
An entirely new security model is needed for the Internet of Things, or is it? Can we save some old and tested controls for this new and different environment? In his session at @ThingsExpo, New York's at the Javits Center, Davi Ottenheimer, EMC Senior Director of Trust, reviewed hands-on lessons with IoT devices and reveal a new risk balance you might not expect. Davi Ottenheimer, EMC Senior Director of Trust, has more than nineteen years' experience managing global security operations and assessments, including a decade of leading incident response and digital forensics. He is co-author of t...
May. 29, 2015 11:00 AM EDT Reads: 6,151
The Internet of Things is a misnomer. That implies that everything is on the Internet, and that simply should not be - especially for things that are blurring the line between medical devices that stimulate like a pacemaker and quantified self-sensors like a pedometer or pulse tracker. The mesh of things that we manage must be segmented into zones of trust for sensing data, transmitting data, receiving command and control administrative changes, and peer-to-peer mesh messaging. In his session at @ThingsExpo, Ryan Bagnulo, Solution Architect / Software Engineer at SOA Software, focused on desi...
May. 29, 2015 11:00 AM EDT Reads: 4,456
The multi-trillion economic opportunity around the "Internet of Things" (IoT) is emerging as the hottest topic for investors in 2015. As we connect the physical world with information technology, data from actions, processes and the environment can increase sales, improve efficiencies, automate daily activities and minimize risk. In his session at @ThingsExpo, Ed Maguire, Senior Analyst at CLSA Americas, will describe what is new and different about IoT, explore financial, technological and real-world impact across consumer and business use cases. Why now? Significant corporate and venture...
May. 29, 2015 10:50 AM EDT Reads: 663
While great strides have been made relative to the video aspects of remote collaboration, audio technology has basically stagnated. Typically all audio is mixed to a single monaural stream and emanates from a single point, such as a speakerphone or a speaker associated with a video monitor. This leads to confusion and lack of understanding among participants especially regarding who is actually speaking. Spatial teleconferencing introduces the concept of acoustic spatial separation between conference participants in three dimensional space. This has been shown to significantly improve comprehe...
May. 29, 2015 10:00 AM EDT Reads: 3,676
Today’s enterprise is being driven by disruptive competitive and human capital requirements to provide enterprise application access through not only desktops, but also mobile devices. To retrofit existing programs across all these devices using traditional programming methods is very costly and time consuming – often prohibitively so. In his session at @ThingsExpo, Jesse Shiah, CEO, President, and Co-Founder of AgilePoint Inc., discussed how you can create applications that run on all mobile devices as well as laptops and desktops using a visual drag-and-drop application – and eForms-buildi...
May. 29, 2015 10:00 AM EDT Reads: 5,848
There will be 150 billion connected devices by 2020. New digital businesses have already disrupted value chains across every industry. APIs are at the center of the digital business. You need to understand what assets you have that can be exposed digitally, what their digital value chain is, and how to create an effective business model around that value chain to compete in this economy. No enterprise can be complacent and not engage in the digital economy. Learn how to be the disruptor and not the disruptee.
May. 29, 2015 09:45 AM EDT Reads: 1,084
The enterprise market will drive IoT device adoption over the next five years. In his session at @ThingsExpo, John Greenough, an analyst at BI Intelligence, division of Business Insider, will analyze how companies will adopt IoT products and the associated cost of adopting those products. John Greenough is the lead analyst covering the Internet of Things for BI Intelligence- Business Insider’s paid research service. Numerous IoT companies have cited his analysis of the IoT. Prior to joining BI Intelligence, he worked analyzing bank technology for Corporate Insight and The Clearing House Pay...
May. 29, 2015 09:36 AM EDT Reads: 656
The Domain Name Service (DNS) is one of the most important components in networking infrastructure, enabling users and services to access applications by translating URLs (names) into IP addresses (numbers). Because every icon and URL and all embedded content on a website requires a DNS lookup loading complex sites necessitates hundreds of DNS queries. In addition, as more internet-enabled ‘Things' get connected, people will rely on DNS to name and find their fridges, toasters and toilets. According to a recent IDG Research Services Survey this rate of traffic will only grow. What's driving t...
May. 29, 2015 09:00 AM EDT Reads: 5,655
With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo in Silicon Valley. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place Nov 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 17th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal an...
May. 29, 2015 09:00 AM EDT Reads: 3,253