Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort Properties in java?

Tags:

I have a Properties object and sometimes I need to add other Properties to it.

Properties myBasicProps = this.getClass.getResourceAsStream(MY_PROPS_PATH); ... Properties otherProps = new Properties(); otherProps.load(new StringReader(tempPropsString)); //tempPropsString contains my temporary properties myBasicProps.putAll(otherProps); 

I want to sort myBasicProps after this. I don't want to get all keys and values, sort them with Collections.sort() and then put it all to a new object. Is there a better way?

like image 849
shift66 Avatar asked Apr 23 '12 06:04

shift66


People also ask

How can we sort a list of elements in Java?

Summary. Collections class sort() method is used to sort a list in Java. We can sort a list in natural ordering where the list elements must implement Comparable interface. We can also pass a Comparator implementation to define the sorting rules.

Can you sort sets in Java?

You can't, since a Set does not have random access methods (ie, . get() an element at a given index), which is basically required for sort algorithms ;) You can't since a HashSet doesn't have a defined order.

What is sorting order in Java?

The sorting is a way to arrange elements of a list or array in a certain order. The order may be in ascending or descending order. The numerical and lexicographical (alphabetical) order is a widely used order.


1 Answers

No, java.util.Properties extends java.util.Hashtable which doesn't define a predictable sort order for keys or values.

You could try dumping all values into something like java.util.TreeMap, which will impose a natural ordering on your keys.

like image 160
harto Avatar answered Sep 17 '22 15:09

harto