24

I'm wondering if it's possible to sort a LinkedHashSet. I've tried the statement

Collections.sort((List<Comparable> paragraph);

However, that just throws an error that it cannot be casted into a List. Is there a way of doing this, or should I use another data structure?

M. Justin
  • 14,487
  • 7
  • 91
  • 130
Matthew Brzezinski
  • 1,685
  • 4
  • 29
  • 53

5 Answers5

32

You should use a SortedSet such as TreeSet or ConcurrentSkipListSet if you care about ordering based on comparison (e.g., sorted order).

A LinkedHashSet preserves order based on insertion order.

If you really want to use Collections.sort you can convert the LHS into a List by actually constructing a List (though the question doesn't tell us the type of paragraph so I'll assume it is String)

List<String> listParagraph = new ArrayList<String>(paragraph);
Collections.sort(listParagraph)

but that's probably not the best approach.

Emil Sit
  • 22,894
  • 7
  • 53
  • 75
4

Collections.sort does not work on Sets, only on Lists. If you need to sort the data that is already in a Set, you might want to first add them into a List.

zw324
  • 26,764
  • 16
  • 85
  • 118
2

You can add LinkedHashSet object (linkedHashSet) to TreeSet and it will be sorted.

TreeSet<T> treeSet = new TreeSet<t>();
treeSet.addAll(linkedHashSet);

treeSet is the sorted set.

Note that you need to make these T type comparable(by implementing Comparator interface).

ajay.patel
  • 1,957
  • 12
  • 15
1

Yes, You can. Java 8 has made our life easier :)

creating a linked list (it looks simple to me, you can directly insert in LinkedHashSet)

LinkedList<String> lList = new LinkedList<String>();
lList.add("Ravi");
lList.add("Vijay");
lList.add("Ravi");
lList.add("Ajay");
lList.add(null);

LinkedHashSet<String> lHashSet = new LinkedHashSet<>();
lHashSet.addAll(lList);

let's sort now

lHashSet.stream().sorted((String s1,String s2)->{       
    return s1.compareTo(s2);
});

//now print it
System.out.println("----");
lHashSet.forEach(action->{
   System.out.println(action);
});
System.out.println("----");

Output-

----
Ravi
Vijay
Ajay
null
----

Happy Coding :)

saurabh gupta
  • 57
  • 1
  • 9
0

If for some reason you really need to sort an existing LinkedHashSet and can't create a new sorted one, you could create a sorted copy of the data, clear the original set, then add all the elements.

TreeSet<String> sortedCopy = new TreeSet<>(linkedHashSet);
linkedHashSet.clear();
linkedHashSet.addAll(sortedCopy);
M. Justin
  • 14,487
  • 7
  • 91
  • 130