Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get nth element of a Set

More specifically: how to get the nth element of a LinkedHashSet (which has a predictable iteration order)? I want to retrieve the nth element inserted into this Set (which wasn't already present).

Is it better to use a List:

List<T> list = new ArrayList<T>(mySet);
T value = list.get(x); // x < mySet.size()

or the toArray(T [] a) method:

T [] array = mySet.toArray(new T[mySet.size()]);
T value = array[y]; // y < mySet.size()

Other than the (likely slight) performance differences, anything to watch out for? Any clear winner?

Edit 1

NB: It doesn't matter why I want the last-inserted element, all that matters is that I want it. LinkedHashSet was specifically chosen because it "defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set."

Edit 2

This question seems to have devolved into a discussion of whether any Set implementation can ever preserve original insertion order. So I put up some simple test code at http://pastebin.com/KZJ3ETx9 to show that yes, LinkedHashSet does indeed preserve insertion order (the same as its iteration order) as its Javadoc claims.

Edit 3

Modified the description of the problem so that everybody isn't too focused on retrieving the last element of the Set (I originally thought that the title of the question would be enough of a hint — obviously I was wrong).

like image 849
markvgti Avatar asked Jun 28 '14 06:06

markvgti


People also ask

How do you find the nth element of a set?

Now, to access an element at nth index we need to create an iterator pointing to starting position and keep on increment the iterator till nth element is reached i.e. std::cout<<"3rd Element in set = "<<*setIt<<std::endl; std::set<std::string>::iterator setIt = setOfStr.

Does set have index in C++?

A set in c++ is an associative(STL) container used to store unique elements that are stored in a specific sorted order(increasing or decreasing). Elements of the set are unique, i.e., no duplicate values can be stored in the set because each value in the set is a key, and the set doesn't support indexing.


3 Answers

This method is based on the updated requirement to return the nth element, rather than just the last element. If the source is e.g. a Set with identifier mySet, the last element can be selected by nthElement(mySet, mySet.size()-1).

If n is small compared to the size of the Set, this method may be faster than e.g. converting to an ArrayList.

  /**
   * Return an element selected by position in iteration order.
   * @param data The source from which an element is to be selected
   * @param n The index of the required element. If it is not in the 
   * range of elements of the iterable, the method returns null.
   * @return The selected element.
   */
  public static final <T> T nthElement(Iterable<T> data, int n){
    int index = 0;
    for(T element : data){
      if(index == n){
        return element;
      }
      index++;
    }
    return null;
  }
like image 186
Patricia Shanahan Avatar answered Oct 16 '22 06:10

Patricia Shanahan


I'd use the iterator of the LinkedHashSet if you want to retrieve the last element:

Iterator<T> it = linkedHashSet.iterator();
T value = null;

while (it.hasNext()) {
    value = it.next();
}

After the loop execution value will be referring to the last element.

like image 45
Juvanis Avatar answered Oct 16 '22 07:10

Juvanis


So I decided to go with a slight variation of the answer by @Juvanis.

To get at the nth element in a LinkedHashSet:

Iterator<T> itr = mySet.iterator();
int nth = y;
T value = null;

for(int i = 0; itr.hasNext(); i++) {
    value = itr.next();
    if (i == nth) {
        break;
    }
}

Version 2 of the code:

public class SetUtil {

    @Nullable
    public static <T> T nthElement(Set<T> set, int n) {
        if (null != set && n >= 0 && n < set.size()) {
            int count = 0;
            for (T element : set) {
                if (n == count)
                    return element;
                count++;
            }
        }
        return null;
    }
}

NB: with some slight modifications the method above can be used for all Iterables<T>.

This avoids the overhead of ensuring that a Set and a List stay in sync, and also avoids having to create a new List every time (which will be more time-consuming than any amount of algorithmic complexity).

Obviously I am using a Set to ensure uniqueness and I'd rather avoid a lengthy explanation as to why I need indexed access.

like image 2
markvgti Avatar answered Oct 16 '22 06:10

markvgti