I got a List in java. I get values from a SQL query.
public void ReloadPages() throws Exception {
try (Connection conn = Framework.GetDatabaseManager().GetBone().getConnection()) {
try (ResultSet set = conn.createStatement().executeQuery("SELECT * FROM habbo_shop_pages")) {
while (set.next()) {
int Id = set.getInt(1);
Pages.put(Id, new CatalogPage(set));
}
}
}
System.out.println("Loaded " + Pages.size() + " Catalog Page(s).");
}
Then I store it all. In another function, I want to retrieve certain pages from a parentid.
public LinkedList<CatalogPage> getSubPages(int parentId) {
LinkedList<CatalogPage> pages = new LinkedList<>();
for (CatalogPage page : this.Pages.values()) {
if (page.getParentId() != parentId) {
continue;
}
pages.add(page);
}
return pages;
}
How do I order the list? Now id 4 is above in the shop and 1 at the bottom, but I want it ordered by id. ORDER BY in query doesn't work.
Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted as the parameter and returns a Collection sorted in the Ascending Order by default.
Though there is no sorted list in Java there is however a sorted queue which would probably work just as well for you. It is the java. util. PriorityQueue class.
Heap sort is one of the most important sorting methods in java that one needs to learn to get into sorting. It combines the concepts of a tree as well as sorting, properly reinforcing the use of concepts from both.
There are multiple ways to sort a list in Java 8, for example, you can get a stream from the List and then use the sorted() method of Stream class to sort a list like ArrayList, LinkedList, or Vector and then convert back it to List. Alternatively, you can use the Collections. sort() method to sort the list.
Have your class implement Comparable
and provide said sort ordering in compareTo
method. And to sort, simply use Collections#sort
, although be aware that it's an inline sort.
You want to sort the list in reverse order then try this:
Collections.sort(list,Collections.reverseOrder());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With