Java LinkedHashSet backwards iteration

后端 未结 5 1861
执念已碎
执念已碎 2020-12-09 16:02

How can I iterate through items of a LinkedHashSet from the last item to the first one?

相关标签:
5条回答
  • 2020-12-09 16:25

    This is another way:

    LinkedHashSet<T> set = ...
    
    List<T> list = new ArrayList<>(set);
    Collections.reverse(list);
    
    for( T item : list ){
       ...
    }
    
    0 讨论(0)
  • 2020-12-09 16:26

    er, assuming you mean LinkedHashSet...

    I would use toArray and just use a reverse for loop.

    There might be a better way to do it, but that should work. toArray guarantees any order is preserved

    If this set makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.

    Something like

    Set<MyType> mySet = new LinkedHashSet();
    ...
    MyType[] asArray = mySet.toArray();
    
    for (int i = asArray.length - 1; i>=0; i--){
    ..
    }
    
    0 讨论(0)
  • 2020-12-09 16:28

    From the javadoc: "This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order)."

    So you can simply:

    LinkedHashSet<Integer> numbers = new LinkedHashSet<Integer>();
    numbers.add(1);
    numbers.add(2);
    numbers.add(33);
    numbers.add(44);
    numbers.add(108);
    
    for (Integer i : numbers) {
        System.out.println(i);
    }
    
    0 讨论(0)
  • 2020-12-09 16:37

    If you really meant LinkedHashSet, you could put the elements into an ArrayList and then use the ArrayList's ListIterator.

    ListIterator<T> l = new ArrayList<T>(yourLinkedHashList).listIterator();
    // ListIterator can iterate in reverse
    while(l.hasPrevious()) {
        T obj = l.previous();
    }
    
    0 讨论(0)
  • 2020-12-09 16:48

    If you want to continue to use collections, you could use the following:

    LinkedHashSet<T> set = ...
    
    LinkedList<T> list = new LinkedList<>(set);
    Iterator<T> itr = list.descendingIterator();
    while(itr.hasNext()) {
        T item = itr.next();
        // do something
    }
    

    If you're fine with using an array instead, you could take a look at hvgotcodes' answer.

    0 讨论(0)
提交回复
热议问题