Java - removeAll

Soldato
Joined
27 Aug 2004
Posts
17,111
Location
Geordieland
I am researching how to use the removeAll and addAll commands in Java, but i am struggling to find anything on the net on how to use these functions, so it would be much appreciated if someone could give me a little advice on how you should set out the code to something like as follows.

I have a range of values in treeSet1, beginning with a range of different letters(say R097483, J86583 and K95732), but in treeSet 2 I want the values out of treeSet1 that contains only the vaues with the first letter being 'R' at charAt[0].

Is this even possible, or am I just trying to to do something that isnt possible to do?

So far ive got to(but it will be way off probably as Ive never used this function before):

treeSet2.addAll(charAt[0]="R"(treeSet1));

Cheers for any help, its much appreciated.
 
Last edited:
Hi,

The easiest way to do this I think would be to iterate through TreeSet1, examine each item to see if it begins "R" and if so copy it to TreeSet2 .

The TreeSet is a collection of objects in their natural order (determined by the Comparator for the object). So, if you're objects are Strings then they'll be ordered by Unicode value of each char. Once you've read the last one starting with "R" e.g starts with "S" or above, you can be assured there are no more.

Try something like this:

Code:
TreeSet<String>mytree1 = new TreeSet<String>();
TreeSet<String>mytree2 = new TreeSet<String>();

for (String s : mytree1) {
    if (s.charAt(0)=='R')
        mytree2.add(s);
};

Other things you might try to something with the binarySearch (static method on the Collections class) to get the position of the first and last elements you want. That might be more efficient. Or I'm sure there are other ways of doing this.

Hope that helps.

Jim
 
Back
Top Bottom