Monday, January 20, 2025
HomeProgrammingHow can I sort a HashSet in Java?

How can I sort a HashSet in Java?

How can I sort a HashSet in Java?

A HashSet is an unordered collection, so you cannot directly sort it. However, you can convert it to a List and sort the list using Collections. Sort. Example:

HashSet<Integer> set = new HashSet<>

set.add (3)

See also  HTML Tag

set.add (1)

set.add (2)

List<Integer> sorted List = new Array List<>(set)

Collections. Sort (sorted List)

Alternatively, you can use Java 8’s Stream API to sort the HashSet:

Set<String> hashSet = new HashSet<>
hashSet.add (“Orange”)
hashSet.add (“Apple”)
hashSet.add (“Banana”)

List<String> sortedList = hashSet.stream
.sorted .collect (Collectors.toList())

See also  How to Indent a Few Lines in Markdown Markup?

System.out.println(sortedList)

This will produce the same output as the previous example.

Note that if you need to maintain a sorted set, you may want to consider using a Tree Set instead of a HashSet. Tree Set is a sorted implementation of the Set interface.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x