Question

I have a SortedSet defined this way:

SortedSet<RatedMessage> messageCollection = new TreeSet<RatedMessage>(new Comp());

and I have an array of RatedMessage[]

I had to use the array as the set misses the serialization feature, now I need to construct it back.

Is there a quick way to add all the items from the array to the set again?

Was it helpful?

Solution

Collections.addAll(messageCollection, array);

Functionally identical to Michael's answer, but as the javadoc says:

Adds all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.

OTHER TIPS

Set has an addAll method, but it only takes a collection, so you'll need to convert the array first:

RatedMessage[] arr;
messageCollection.addAll(Arrays.asList(arr));

You can add RatedMessage[] array into SortedSet using Arrays.asList with TreeSet

String RatedMessage[]={"1","2","3","1","4","3"};
SortedSet lst= new TreeSet(Arrays.asList(RatedMessage));
Iterator it = lst.iterator();
        while(it.hasNext())
        {
            Object ob= it.next();
            System.out.println(ob);
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top