java List集合中针对一个或多个属性进行排序
Post:2019-12-24 18:03:30
Tags:/
java
/
Visit:
1.单个属性排序
1 2 3 4 5 6 7 8 9 10 11 12 13
| List<String[]> list=new LinkedList<>(); list.add("3"); list.add("1"); list.add("2"); Collections.sort(list, new Comparator<String[]>() { @Override public int compare(String[] front, String[] behind) { return front[0].compareTo(behind[0]); return behind[0].compareTo(front[0]); } });
|
2.多属性及条件排序
1 2 3 4 5 6 7 8 9
| Collections.sort(list, new Comparator<String[]>() { @Override public int compare(String[] front, String[] behind) { if (front[0].equals(behind[0])) { return behind[1].compareTo(front[1]); } else return behind[0].compareTo(front[0]); } });
|
3.依据某个属性条件及数据类型排序
1 2 3 4 5 6 7 8 9
| Collections.sort(list, new Comparator<String[]>() { @Override public int compare(String[] front, String[] behind) { if (front[0].equals(behind[0])) { return Double.compare(Double.parseDouble(behind[1]),Double.parseDouble(front[1])); } else return Double.compare(Double.parseDouble(behind[0]),Double.parseDouble(front[0])); } });
|
4.Lambda表达式排序
1 2 3 4
| list = list.stream().sorted((front, behind) -> front.[0].compareTo(behind[0])).collect(Collectors.toList());
list = list.stream().sorted((front, behind) -> behind.[0].compareTo(front[0])).collect(Collectors.toList());
|