Total Pageviews

2015/04/29

How to sort list of Java object with multiple fields

Problem
Assume I have a Java bean which named Fms432fa
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@Data
public class Fms432fa implements Serializable {
    // default serial version id, required for serializable classes.
    private static final long serialVersionUID = 1L;

    private BigDecimal befalc1;
    private String accyr;
    private String dataType;
    private String rptNo;
    private BigDecimal alc1;
    private BigDecimal alc2;
    private BigDecimal alc3;
    private BigDecimal alc4;
    private BigDecimal alc5;
    private BigDecimal alc6;
    private BigDecimal alc7;
    private BigDecimal alc8;
    private BigDecimal alc9;
    private BigDecimal alc10;
    private BigDecimal alc11;
    private BigDecimal alc12;
    private String userid;
    private String updDateTime;

    /** {@inheritDoc} */
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

}

If I have a List of Fms432fa, and I would like to sort it by accyr, dataType and rptNo. How to do it?

Solution
Utilize Google Guava to fulfill this sorting requirement
1
2
3
4
5
6
7
8
        Collections.sort(fms432fas, new Comparator<Fms432fa>() {
            @Override
            public int compare(Fms432fa o1, Fms432fa o2) {
                return ComparisonChain.start().compare(o1.getAccyr(), o2.getAccyr())
                        .compare(o1.getDataType(), o2.getDataType())
                        .compare(o1.getRptNo(), o2.getRptNo()).result();
            }
        });


Reference
[1] http://blog.projectnibble.org/2013/06/21/ways-to-sort-lists-of-objects-in-java-based-on-multiple-fields/ 

No comments: