Reputation: 1249
Can someone suggest me a datatype/structure in java that satisfies: 1) no fixed size 2) does not automatically sort data. Data should be stored in the order in which it arrives 3) it should store only unique entries 4) its elements are accessible or atleast the first element should be!
links are not able to maintain unique entries. I tried working with Sets but it changes the order of my data automatically which i dont want to let happen. So i am now trying to work my way with LinkedHashSet, but I am not able to find the exact way to access the first element of the same for comparision.
Any suggestions please. Thanks!
Upvotes: 2
Views: 99
Reputation: 366
If I properly understand your question, you are looking for a data structure that would combine the properties of a Set and an ArrayList, a kind of "ArraySet".
I haven't found anything in the core java for that but it looks like the Android JDK has such a data structure.
https://developer.android.com/reference/android/util/ArraySet.html https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/util/ArraySet.java
One solution might be to build your own based on the android implementation.
Upvotes: 0
Reputation: 14829
LinkedHashSet
is the right data structure for your requirements.
You can access the first element like so:
Set<String> set = new LinkedHashSet<>();
set.add("a");
set.add("b"); // And so on
// Retrieve first element
// Will throw NoSuchElementException if set is empty
String firstElement = set.iterator().next();
// Retrieve and remove first element
Iterator<String> i = set.iterator();
String otherFirstElement = i.next();
i.remove();
For accessing other elements, see answer from @Whatzs.
Upvotes: 2
Reputation: 5592
You can use LinkedHashSet
if you don't wanna write your own structure. Getting elements may be kinda tricky, try this:
Integer lastInteger = set.stream().skip(set.size()-1).findFirst().get();
This is gonna get the last element, if you want different elements you need to skip a different count. This is only one of the ways, you can get an iterator and iterate yourself etc. Remember to override hashCode
and equals
when working with sets.
Upvotes: 4