I have a difficult question in sorting with the archive.
I have a hushmap, in which something is the following
hashmap & lt; String, quote bean & gt; MapToSort = New Hashmap & lt; & Lt; String, quote bean & gt; ();
Quote Bean is basically a Java Bean that has properties with setter and greater methods, which look like the following.
// class quote bean defination class expressions bean serializable {private bigdevelopment current pixel private transitional change; Private BigDelletchange; Private string symbol; //
with getter and setter methods} Now when I get values from the map, I usually like it
< Code> store value = mapToSort.values (); // which will return all values in the map
This value is basically a collection of quote bean items. I want to sort the beans before sending it to the customer. Now I can use the comparator interface and sort it. But the problem is that the sorting criteria often change. I mean some time the customer wants to sort with the signal, some time the customer with the total profit Want to change over time? Criteria often changes often, is there a way to write "comparison" function overload and that will satisfy all the conditions ...
C is a good way of solving problems ..
Yes. Apply the interface and use the overloaded method: Collections.sort (list, comparator)
(You will need to create a new list
from the collection elements, for example < Code> New Array List (Collection) )
You can do the following:
Public CurrentProjectQuoteComparator Comparator applies & quot; QuoteBean & gt; Compare {@ Override Public Int (Quote Bean B1, Coat Bean B2) {// Comparison of Implementation}} Public Changes Compatator Tools Companator & lt; QuoteBean & gt; Compare {@ Override Public Int (Quote Bean B1, Coat Bean B2) {// Comparison of Implementation}}
and then use the store. Source (List, Changzhou Comparator. INSTANCE);
Note that this is a good practice to declare the singleton frequency of each comparator instead of instantiating it:
Public stable final ChangeQuoteComparator INSTANCE = new ChangeQuoteComparator ();
To expand some more things, you can define a enum
with different comparison types:
public key comparison type {CHANGE, CURRENT_PRICE; // etc ..}
and define map
to match each comparison type with the proper comparator:
Private stationary last map & lt; Comparison type, comparative & lt; QuoteBean & gt; & Gt; Comparators = new hashmapmark & lt; Comparison type, comparative & lt; Quotebean & gt; & Gt; (); Stable {comparators.put (comparison type. CHANGE, ChangeQuoteComparator.INSTANCE); Comparators.put (comparison type. CURENT_PRICE, CurrentPriceQuoteComparator.INSTANCE); }
and then specify the comparison that the client should want to compare
public list & lt; QuoteBean & gt; GetOrdered (Comparison Type Type, // Other Criteria) {List & quot; QuoteBean & gt; List = new arreelist & quot; Quote Bean & gt; (GetQuotesCollection ()); Collections.sort (list, comparators.get) (type)); Return list; }
Comments
Post a Comment