Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

Does a Java Set retain order? A method is returning a Set to me and supposedly the data is ordered but iterating over the Set, the data is unordered. Is there a better way to manage this? Does the method need to be changed to return something other than a Set?

1 Answer

0 votes
by (119k points)

Set is just an interface. To retain order, you need to use a specific implementation of that interface and the sub-interface SortedSet, for example, you can use either TreeSet or LinkedHashSet. You can wrap your Set in the following way:

Set myOrderedSet = new LinkedHashSet(mySet);

I recommend this Java course by Intellipaat if you want to learn Java.

Related questions

0 votes
1 answer
asked Aug 15, 2019 in Java by Krishna (2.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Nov 13, 2019 in Java by Nigam (4k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...