In the recent development process, we encountered , according to bean In the case of sorting multiple fields in a class , Take this opportunity to put the relevant sorting practices , Just sort it out and back it up .

1.list Simple ordering of

2.list Element is bean The situation of , according to bean Sort by one of the attributes of

3.list Element is bean The situation of , according to bean Sort multiple attributes of

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map; import cn.com.ydd.bean.SortBean;
import cn.com.ydd.util.CommonUtil; public class SortTest {
public static void main(String[] args) { //1、 He Chun なリストをソートする example
ArrayList lst = new ArrayList();
lst.add("00000000001");
lst.add("00000000002");
lst.add("00000000003");
lst.add("00000000004");
lst.add("00000000005");
// He Chun なリストをソートする example ( Sheng Shun )
Collections.sort(lst);
System.out.println(lst.toString());
// He Chun なリストをソートする example ( Surrendering )
Collections.reverse(lst);
System.out.println(lst.toString());
//2、LISTに a っているbeanのある attribute をキーとしてソートする example
List<SortBean> list = new ArrayList<SortBean>();
SortBean sb;
sb = new SortBean();
sb.setId("00001");
sb.setName(" Tanaka ");
sb.setSex("F");
list.add(sb); sb = new SortBean();
sb.setId("00002");
sb.setName(" Sato ");
sb.setSex("M");
list.add(sb); sb = new SortBean();
sb.setId("00003");
sb.setName(" Sato ");
sb.setSex("M");
list.add(sb); sb = new SortBean();
sb.setId("00004");
sb.setName(" Sato ");
sb.setSex("M");
list.add(sb); sb = new SortBean();
sb.setId("00005");
sb.setName(" Yamamoto ");
sb.setSex("F");
list.add(sb); sb = new SortBean();
sb.setId("00006");
sb.setName(" Yamamoto ");
sb.setSex("F");
list.add(sb); // Surrendering
System.out.println("***********name: Surrendering *************");
CommonUtil.sort(list, "name", false);
for(SortBean item : list){
System.out.print(item.getId()+" ");
System.out.print(item.getName()+" ");
System.out.println(item.getSex());
}
// Sheng Shun
System.out.println("***********name: Sheng Shun *************");
CommonUtil.sort(list, "name", true);
for(SortBean item : list){
System.out.print(item.getId()+" ");
System.out.print(item.getName()+" ");
System.out.println(item.getSex());
} System.out.println("***********name: Sheng Shun ID: Surrendering *************");
//3、LISTに a っているbeanの Plural attribute をキーとしてソートする example
Map<String, String> sortParam = new LinkedHashMap<String, String>();
//name: Sheng Shun ID: Surrendering
sortParam.put("name", "asc");
sortParam.put("id", "desc");
CommonUtil.sortExecute(list, sortParam); for(SortBean item : list){
System.out.print(item.getId()+" ");
System.out.print(item.getName()+" ");
System.out.println(item.getSex());
}
sortParam.clear();
//name: Sheng Shun ID: Sheng Shun
sortParam.put("name", "desc");
sortParam.put("id", "asc");
CommonUtil.sortExecute(list, sortParam);
System.out.println("***********name: Surrendering ID: Sheng Shun *************");
for(SortBean item : list){
System.out.print(item.getId()+" ");
System.out.print(item.getName()+" ");
System.out.println(item.getSex());
}
}
}

Common method classes

import java.util.Comparator;
import java.util.List;
import java.util.Map; import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections4.ComparatorUtils;
import org.apache.commons.collections4.comparators.ComparableComparator;
import org.apache.commons.collections4.comparators.ComparatorChain;
import org.apache.commons.collections4.comparators.NullComparator; public class CommonUtil { /**
* beanのある attribute によってソートする Occasion
* @param list
* @param filedName
* @param ascFlag
*/
@SuppressWarnings("unchecked")
public static void sort(List list, String filedName, boolean ascFlag) { if (list.size() == 0 || filedName.equals("")) {
return;
}
Comparator<?> cmp = ComparableComparator.INSTANCE;
// Surrendering の Occasion
if (ascFlag) {
cmp = ComparatorUtils.nullLowComparator(cmp);
} else {
cmp = ComparatorUtils.reversedComparator(cmp); }
Collections.sort(list, new BeanComparator(filedName, cmp));
} /**
* beanのある attribute によってソートする Occasion
* @param beans
* @param sortParam
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void sortExecute(List<?> beans, Map<String, String> sortParam) { // The results are as follows リスト To the elephant またはソースパラメータ To the elephant がNULLである Occasion
if (beans.size() == 0 || sortParam.keySet().size() == 0) {
// It's over
return;
} // The results are as follows リスト To the elephant またはソースパラメータ To the elephant のサイズがゼロ Pieces of の Occasion
if (beans.isEmpty() || sortParam.isEmpty()) {
// It's over
return;
}
ComparatorChain comparator = new ComparatorChain();
boolean sortMethod = false;
for (String itemName : sortParam.keySet()) {
sortMethod = false;
if ("desc".equals(sortParam.get(itemName))) {
sortMethod = true;
}
comparator.addComparator(new BeanComparator(itemName, new NullComparator()), sortMethod);
}
Collections.sort(beans, comparator);
} }

Output results

[00000000001, 00000000002, 00000000003, 00000000004, 00000000005]
[00000000005, 00000000004, 00000000003, 00000000002, 00000000001]
***********name: Surrendering *************
00001 Tanaka F
00005 Yamamoto F
00006 Yamamoto F
00002 Sato M
00003 Sato M
00004 Sato M
***********name: Sheng Shun *************
00002 Sato M
00003 Sato M
00004 Sato M
00005 Yamamoto F
00006 Yamamoto F
00001 Tanaka F
***********name: Sheng Shun ID: Surrendering *************
00004 Sato M
00003 Sato M
00002 Sato M
00006 Yamamoto F
00005 Yamamoto F
00001 Tanaka F
***********name: Surrendering ID: Sheng Shun *************
00001 Tanaka F
00005 Yamamoto F
00006 Yamamoto F
00002 Sato M
00003 Sato M
00004 Sato M

About java sort Several ways to realize ( Simple sorting , according to bean One of the fields of , according to bean Multiple fields for ) More articles about

  1. Java There are three ways to implement multithreading

    java There are three ways to implement multithreading One . Inherit Thread class Two . Realization Runnable Interface 3、 ... and . Use ExecutorService, Callable, Future Whether through inheritance Thread Class or implementation Ru ...

  2. java Several ways to implement multithreading

    java Several ways to implement multithreading 1. Inherit Thread class , rewrite run Method 2. Realization Runnable Interface , rewrite run Method , Realization Runnable The instance object of the implementation class of the interface is used as Thread Constructor's target3. through ...

  3. java There are three ways to implement proxy

    Java There are several ways to implement the proxy model : 1. Static proxy . 2.JDK A dynamic proxy . 3.CGLIB A dynamic proxy . Example , There's a greeting interface . There are two implementations , say hello, And shake hands . The code is as follows . Interface : public ...

  4. Java Several ways to implement timed tasks

    JAVA There are several ways to realize timing task @(JAVA)[spring|quartz| Timer ]  In recent project development, we need to dynamically add scheduled tasks , For example, at the end of an activity , Automatically generate a list of winners , export excel etc. , Such tasks are due to activities ...

  5. Java There are two ways to implement multithreading

    Java There are two ways to implement multithreading The way 1: By inheritance Thread Kind of the way package com.day04; /** * By inheritance Thread Class and copy run The method is to implement multithreading * * @author ...

  6. XML Basics +Java analysis XML + Performance comparison of several parsing methods

    XML Basics +Java analysis XML One :XML Basics XML What is it? : Extensible markup language XML Can do : Describe the data . Store the data . transmission ( In exchange for ) data . XML And HTML difference : The purpose is different XML Designed to describe numbers ...

  7. Alibaba --java There are two ways to implement multithreading , And the difference between the two

    When Alibaba interviewed , Asked me yesterday java Do it in an interview java Two ways of multithreading , As well as the difference between the two, only two ways to implement threads were answered at that time , But there is no answer to the difference between the two : java There are two ways to implement multithreading : 1. Inherit Thre ...

  8. java Of list The efficiency of several ways of implementation (ArrayList、LinkedList、Vector、Stack), as well as java Comparison of three ways to obtain timestamps

    One .list brief introduction List List class , Store any object in sequence ( The order is the same ), repeatable . List It is inherited from Collection The interface of , Can't instantiate . Instantiation can use : ArrayList( Implementation of dynamic array ), Quick query ( Feel free to visit or ...

  9. Java There are three ways to realize timer

    One . Ordinary thread /** * Ordinary thread * This is the most common , Create a thread, And then let it be in while It's running all the time in the loop , * adopt sleep Methods to achieve the effect of timing task . This can be implemented quickly and easily , ...

Random recommendation

  1. Highcharts Use the tutorial (1): Make simple charts

    Today we're going to use JavaScript Chart Highcharts Make a simple column chart , We have installed Highcharts, Let's start charting . Step one Add a div. Set up id, Set chart length . high . Code such as ...

  2. LPTHW Stupid law enforcement python 37 Chapter python keyword / Key words Introduction

    This chapter briefly introduces all kinds of keywords : and:[ Boolean operation ] And del: Delete variables ( function , class ) from: Read from a library or file not:[ Boolean operation ] Not while: while-loop keyword , Follow the loop bar ...

  3. Struts frame ——( Two )Struts principle with Login instance

    Two . Struts Basic workflow Suppose we have the following scenario : The user is browsing a page with STRUTS Technology to build the website home page , There's a login form on the home page , The user fills in the login name and password , single click " land " Button , It activates the following ...

  4. Silverlight 4 Commonly used StringFormat Format summary

    Original address :http://www.silverlightchina.net/html/tips/2011/0424/7149.html stay Silverlight In the project , Often according to different needs , Provide different words ...

  5. mysql Remote connection failed (linux)

    There are three main reasons :1.mysql There is no permission for the remote machine in the authorization table , And need to be in the authorization form mysql.user add to grant all privileges on *.* to 'root'@' Remote login IP' ident ...

  6. Protected Member Access

    https://msdn.microsoft.com/en-us/library/bcd5672a.aspx Official statement The protected keyword is a member access ...

  7. NOIP2014 Joint weights

    2. Joint weights (link.cpp/c/pas) [ Problem description ] Undirected connected graph G Yes n A little bit ,n-1 side . Point from 1 To n Number in sequence , The number is i The weight of the point is Wi  , The length of each edge is 1. Two points on the picture (u, v) The distance is defined as u ...

  8. How to be in SSASserver Do synchronization between

     Brief introduction : from SQL Server 2005 Start , The analysis service supports the function of synchronization . This article will introduce how to SQL Server 2012 Next sync Adventureworks Analysis service database of . Through the function of synchronization , I ...

  9. EF Performance test for querying millions of data

    One . cause   Personally, I prefer EF Of , After all, you don't have to write Sql, High development efficiency , It's easy to operate , But I always listen to people EF The performance is not very good , I've seen tests done by others , But I thought it was like that . But what's actually going on , To be honest, I really don't know . ...

  10. List Query the number of duplicate values , And arrange them according to the number of repetitions

    package ttt; import java.nio.MappedByteBuffer; import java.util.ArrayList; import java.util.Collecti ...