Starting Index Index HashSet

I use HashSet methods for add(); remove(); clear(); iterator();. So far, everything has worked like a charm. However, now I need to fulfill another requirement.

I would like to be able to start the iteration from a specific index. For example, I would like the following two programs to have the same output.

Program 1

Iterator it=map.iterator();
for(int i=0;i<100;i++)
{
    it.next();
}
while (it.hasNext())
{
  doSomethingWith(it.next());
}

Program 2

Iterator it=map.iterator(100);
while (it.hasNext())
{
  doSomethingWith(it.next());
}

The reason I don't want to use program 1 is because it creates unnecessary overhead. From my research, I could not find a practical way to create an iterator with an initial index.

So my question is, what would be a good way to achieve my goal while minimizing overhead?

Thank.

+3
source share
5 answers

, add(), remove() HashSet. .

, , . , . , , . , , , .

(, Set<Integer> set = new HashSet<Integer>(); - :

List<Integer> list = new ArrayList<Integer>(set);
list.subList(100, list.size()).iterator(); // this will get your iterator.
+5

HashSet . , , .

:

HashSet set = new HashSet();
//......
ArrayList list = new ArrayList(set);
+2

HashSet , , 100 .

.

Iterator it = map.iterator();
int n = map.size() - 100;
for (int i = 0; i < n; i++)
    doSomethingWith(it.next());
+2

NavigableMap. ( ), .

Map<K,V> submap = navigableMap.tailMap(fromKey);

, () . , , .

K fromKey = new ArrayList<K>( navigableMap.keySet() ).get(index);

, .

+1

@toader.

for(Integer i : new ArrayList<Integer>(set).subList(100, set.size())) {
   // from the 100'th value.
}

Note: the nth value does not matter using a HashSet. You might need a SortedSet, in which case 100th place will be the 100th largest value.

0
source

Source: https://habr.com/ru/post/1784109/


All Articles