how to iterate a linkedhashset starting from a specific element in java?
how to iterate a linkedhashset starting from a specific element in java?
I have a linkedhashset containing these names
[Raj,Anusha,Suresh,Sashant,Tisha,Prajyoti,Shubhavi,Daniel]
I want to iterate this linkedhashset starting from Sashant to Daniel.
String item1;
for (String key : list1)
item1 = key;
System.out.println(item1);
The above code prints all the names from the linkedhashset. How do i print from a specific name (from Suresh to Daniel)? Please help. Thanks.
2 Answers
2
This is not possible with the data structure you are trying to use. Under the hood, a doubly-linked list is used to iterate through the list which does not explicitly allow you to jump to an index.
Suggestions (in order of preference):
An example of what 2 may look like:
String firstNameToPrint = "Some Name";
boolean foundFirstNameToPrint = false;
for (String key : list1)
if (key.equals(firstNameToPrint)
foundFirstNameToPrint = true;
if (foundFirstNameToPrint)
System.out.println(key);
I'll add it as an edit, hold on.
– Eric Le Fort
Sep 8 '18 at 3:33
If your aim is to iterate the elements in chronological order of their insertion into hashset, you may try the data structure consisting of a hashset and List.
Whenever you add a String into hashset, you add it into List as the last element. That takes constant time.
Whenever you remove a String from hashset, you remove it from List as well. That takes linear time.
And whenever you want to iterate from specific element, you use indexOf(String s) to find the index and start iterating from that index.
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
how to implement the 2nd preference that you suggested? using same data structure
– dayl fds
Sep 8 '18 at 3:22