0 votes
1 view
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 (72.4k 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 (4.1k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...