I\'m wondering if it\'s possible to sort a LinkedHashSet. I\'ve tried the statement
Collections.sort((List
Howeve
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).
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.
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 :)
Collections.sort does not work on Set
s, only on List
s. If you need to sort the data that is already in a Set
, you might want to first add them into a List
.