Convert list to set by ImmutableSet.copyOf() and new HashSet<>(list);

Good day,

I have a set that contains some data:

Set< AItem > aItems = aItem
                    .getItems( );

Because I want to do some sorting, so I convert it to list first, after sort, then only turn it back to set:

List< AItem > tempoAccounts = new ArrayList(aItems);

Collections.sort(tempoAccounts, new Comparator() {
                public int compare(Object arg0, Object arg1) {
                    // sorting logic here
                }
            });

// convert from list back to set
aItems = ImmutableSet.copyOf(tempoAccounts);

This give me a correct result, all my data sort accordingly.

However, If I want to add more item into aItems:

AItem aai = new AItem();
            aai.setAId( (long) 2222 );
            aai.setLimit( BigDecimal.ZERO );

then I will hit :

Exception created : [java.lang.UnsupportedOperationException
    at com.google.common.collect.ImmutableCollection.add(ImmutableCollection.java:91)

So I change the

aItems = ImmutableSet.copyOf(tempoAccounts);

to

aItems = new HashSet<AItem>(tempoAccounts);

This will not give me UnsupportedOperationException if I add new item inside this Set. But my sorting is gone, the Set is not sort properly.

Any ideas to sort my Set, and then can add more item inside without exception?

Kindly advise.

Jon Skeet
people
quotationmark

HashSet should be viewed as an unordered set. If you want a sorted set, just use a TreeSet:

Set<AItem> sortedItems = new TreeSet<>(new Comparator<AItem>() { ... });
sortedItems.addAll(aItems);

(Don't use the raw type of Comparator, btw... try to avoid raw types entirely.)

No need to create a list, no need to create an immutable set...

people

See more on this question at Stackoverflow