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);







how to implement the 2nd preference that you suggested? using same data structure

– dayl fds
Sep 8 '18 at 3:22






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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)