开发者

Accessing elements in a treeset

I am attempting some very basic java here and have reached a bit of a head scratcher. Essentially,I need to read some element from a file into some type of array or list, sort them, eliminate duplicates, and then return the first three elements. TreeS开发者_如何转开发et seemed like the perfect fit in so much as it does the sort and kills the duplicates. My issue is that I am confounded as to how to return only the first three elements. The iterator seems to run all the way through the set. Creating a while loop with a manual iterator to contain a while loop that holds the iterator loops seems confusing and unlikely to be successful. Is the answer here that I need to iterate through the treeset and place each element into an arraylist so that I can then access the first three elements? I mean, it seems that this would work but it seems highly convoluted. Tips?


Using Guava you could just do

return Lists.newArrayList(Iterables.limit(treeSet, 3));


Hm. What's wrong with the obvious?

ArrayList<MyType> buffer = new ArrayList<MyType>(3); 

for( MyType elt: myTreeSet ) {

    buffer.add(elt);
    if( buffer.size() == 3 ) break;
}

Or

ArrayList<MyType> buffer = new ArrayList<MyType>(3);
Iterator<MyType> iter = myTreeSet.iterator();

while( iter.hasNext() && buffer.size() < 3 ) buffer.add(iter.next());

if you prefer the "desugared" version?


Example with Strings:

TreeSet<String> treeSet = new TreeSet<String>(); 

// you populate treeSet with data

String[] stringArray = new String[NUMBER_OF_NEEDED_RECORDS];
for(int i =0; i < NUMBER_OF_NEEDED_RECORDS; i++) {
    stringArray[i] = treeSet.pollFirst();
}


I would use (expecting you use Java 1.6):

Arrays.copyOf(myTreeSet.toArray(), Math.min(3, myTreeset.size()));

Edit: to be bulletproof with the size I added Math.min()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜