How to sort the List of SelectItem

A List of SelectItems that are often used to set choices. You may want to sort by using the value obtained from the database. For such a case.

--Environment - CentOS Linux release 7.8.2003 (Core) - openjdk version "11.0.7" 2020-04-14 LTS - JSF 2.3.9

For example, when there is a List of SelectItem like this

value label
1 Dog
3 Monkey
0 Bear
2 Cat
/**List of SelectItems. */
@Getter
private List<SelectItem> items;

/**Set a list of SelectItems. */
private void setItems() {
    this.items = new ArrayList<SelectItem>();
    this.items.add(new SelectItem(1, "Dog"));
    this.items.add(new SelectItem(0, "Bear"));
    this.items.add(new SelectItem(3, "Monkey"));
    this.items.add(new SelectItem(2, "Cat"));
}

Sort in ascending order of value

Reference: [Collections (Java Platform SE 8)](https://docs.oracle.com/javase/jp/8/docs/api/java/util/Collections.html#sort-java.util.List-java. util.Comparator-)

value label
0 Bear
1 Dog
2 Cat
3 Monkey
Collections.sort(this.items, new Comparator<SelectItem>() {
    @Override
    public int compare(SelectItem item1, SelectItem item2) {
        if (item1 != null && item2 != null) {
            if (item1.getValue() != null && item2.getValue() != null) {
                return item1.getValue().toString().compareTo(item2.getValue().toString());
            }
        }
        return 0;
    }
});

(Bonus) Get the minimum value of value

SelectItem minItem = Collections.min(this.items, new Comparator<SelectItem>() {
    //The content is the same as sorting
});
var min = Integer.valueOf(minItem.getValue().toString());

Sort by descending value

Reference: Comparator (Java Platform SE 8)

value label
3 Monkey
2 Cat
1 Dog
0 Bear
//I just reversed item1 and item2 in the ascending return
Collections.sort(this.items, new Comparator<SelectItem>() {
    @Override
    public int compare(SelectItem item1, SelectItem item2) {
        if (item1 != null && item2 != null) {
            if (item1.getValue() != null && item2.getValue() != null) {
                return item2.getValue().toString().compareTo(item1.getValue().toString());
            }
        }
        return 0;
    }
});

Sort by label ascending order

Reference: Sort the list of hiragana and alphabets --Qiita

value label
1 Dog
0 Bear
3 Monkey
2 Cat

Comparator.How to use comparing


this.items = this.items.stream().sorted(Comparator.comparing(SelectItem::getLabel)).collect(Collectors.toList());

Collator.How to use getInstance


Collections.sort(this.items, new Comparator<SelectItem>() {
    @Override
    public int compare(SelectItem item1, SelectItem item2) {
        if (item1 != null && item2 != null) {
            if (item1.getLabel() != null && item2.getLabel() != null) {
                return Collator.getInstance(Locale.JAPANESE).compare(item1.getLabel(), item2.getLabel());
            }
        }
        return 0;
    }
});

Sort in descending order of label

value label
2 Cat
3 Monkey
0 Bear
1 Dog

Comparator.How to use comparing


// reversed()In descending order
this.items = this.items.stream().sorted(Comparator.comparing(SelectItem::getLabel).reversed()).collect(Collectors.toList());

Collator.How to use getInstance


//I just reversed item1 and item2 in the ascending return
Collections.sort(this.items, new Comparator<SelectItem>() {
    @Override
    public int compare(SelectItem item1, SelectItem item2) {
        if (item1 != null && item2 != null) {
            if (item1.getLabel() != null && item2.getLabel() != null) {
                return Collator.getInstance(Locale.JAPANESE).compare(item2.getLabel(), item1.getLabel());
            }
        }
        return 0;
    }
});

What failed when trying to sort

I found a useful thing called Comparator, so I tried to use it immediately and failed. A compilation error occurs around Comparator.comparing (SelectItem :: getValue). Since the value of SelectItem is Object, can't it be used as a sort key?

this.items = this.items.stream().sorted(Comparator.comparing(SelectItem::getValue)).collect(Collectors.toList());

Recommended Posts

How to sort the List of SelectItem
How to delete / update the list field of OneToMany
[Rails] How to display the list of posts by category
How to sort a List using Comparator
How to determine the number of parallels
Add empty data to the top of the list
Customize how to divide the contents of Recyclerview
How to get today's day of the week
Output of how to use the slice method
How to display the result of form input
[Java] How to get the authority of the folder
[Java] How to get the URL of the transition source
How to write Scala from the perspective of Java
[Ruby] How to find the sum of each digit
How to install the root certificate of Centos7 (Cybertrust)
[Java] How to get the maximum value of HashMap
[SwiftUI] How to specify the abbreviated position of Text
[Android] How to get the setting language of the terminal
[Rails] How to get the contents of strong parameters
How to judge the click of any area of the image
Java: Use Stream to sort the contents of the collection
How to download the old version of Apache Tomcat
[Swift] How to get the document ID of Firebase
How to display the select field of time_select every 30 minutes
How to connect the strings in the List separated by commas
How to get the longest information from Twitter as of 12/12/2016
How to change the setting value of Springboot Hikari CP
[Ruby] How to retrieve the contents of a double hash
How to add elements without specifying the length of the array
Let's summarize how to extend the expiration date of Rails
How to solve the problems of Java's three Blocking Queues
How to mock some methods of the class under test
How to derive the last day of the month in Java
How to change the contents of the jar file without decompressing
How to check the extension and size of uploaded files
[jsoup] How to get the full amount of a document
How to check the database of apps deployed on Heroku
How to use the link_to method
[Java] Delete the elements of List
How to use the include? method
How to use the form_with method
How to find the average angle
Sort a List of Java objects
How to use setDefaultCloseOperation () of JFrame
Official logo list of the service
[Java] How to use List [ArrayList]
How to add the delete function
[Rails] How to get the URL of the transition source and redirect
How to set the IP address and host name of CentOS8
How to display 0 on the left side of the standard input value
[Rails / Heroku / MySQL] How to reset the DB of Rails application on Heroku
How to display products by category on the same list screen
How to get the contents of Map using for statement Memorandum
[Rails] How to omit the display of the character string of the link_to method
[Rails] How to change the page title of the browser for each page
How to get the id of PRIMAY KEY auto_incremented in MyBatis
How to output a list of strings in JSF as comma-separated strings
I examined the concept of the process to understand how Docker works
[chown] How to change the owner of a file or directory
How to check for the contents of a java fixed-length string
How to get the length of an audio file in java