Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java sorting List

Tags:

java

list

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.

like image 622
user2199080 Avatar asked Mar 23 '13 11:03

user2199080


People also ask

Can we sort ArrayList in Java?

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.

Does Java have Sortedlist?

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.

Which is best for sorting in Java?

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.

How do you sort an ArrayList in Java 8?

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.


2 Answers

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.

like image 148
mre Avatar answered Sep 20 '22 18:09

mre


You want to sort the list in reverse order then try this:

Collections.sort(list,Collections.reverseOrder());
like image 23
Achintya Jha Avatar answered Sep 20 '22 18:09

Achintya Jha