Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add to SortedSet items from an Array?

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?

like image 453
Pentium10 Avatar asked Jun 28 '10 22:06

Pentium10


People also ask

How do I add values to a sorted set?

The add() method of SortedSet in Java is used to add a specific element into a Set collection. The function adds the element only if the specified element is not already present in the set else the function returns False if the element is already present in the Set.

Is SortedSet an interface?

SortedSet<String> sub = s. subSet(low+"\0", high); This interface is a member of the Java Collections Framework.

When should I use SortedSet?

A SortedSet contains only unique elements and is used to store data in a collection that needs to be in sorted order. By default, the elements of a SortedSet are in ascending order.

What is SortedSet in Java?

The SortedSet interface of the Java Collections framework is used to store elements with some order in a set. It extends the Set interface.


2 Answers

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.

like image 137
ColinD Avatar answered Sep 30 '22 05:09

ColinD


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));
like image 21
Michael Mrozek Avatar answered Sep 30 '22 03:09

Michael Mrozek