自然順序(Comparator.naturalOrder()) を使うなら TestDto
に Comparable
を implements してそちらで id=null の場合の並びを制御するのが妥当では無いでしょうか。
そしたら後は Comparator.nullsLast
と組み合わせるだけです。
java
1 import java . util . * ;
2
3 public class Main {
4 public static void main ( String [ ] args ) throws Exception {
5 List < TestDto > list = new ArrayList < > ( Arrays . asList ( new TestDto ( 2 , "b" ) , null , new TestDto ( null , "c" ) , new TestDto ( 1 , "a" ) ) ) ;
6 System . out . println ( "init. : " + list ) ;
7
8 list . sort ( Comparator . nullsLast ( Comparator . naturalOrder ( ) ) ) ; //自然順序(null は後ろ)
9
10 System . out . println ( "sorted: " + list ) ;
11 }
12 }
13
14 class TestDto implements Comparable < TestDto > {
15 private Integer id ;
16 private String nm ;
17
18 TestDto ( Integer id , String nm ) {
19 this . id = id ;
20 this . nm = nm ;
21 }
22
23 int getId ( ) { return id ; }
24 String getNm ( ) { return nm ; }
25
26 //自然順序
27 @Override
28 public int compareTo ( TestDto o ) {
29 if ( id == null || o . id == null ) return id == o . id ? 0 : id == null ? 1 : - 1 ; //id=null は後ろ
30 return id . compareTo ( o . id ) ;
31 }
32
33 @Override
34 public int hashCode ( ) {
35 return Objects . hash ( id , nm ) ;
36 }
37 @Override
38 public boolean equals ( Object other ) {
39 if ( other == null ) return false ;
40 if ( other == this ) return true ;
41 if ( ! ( other instanceof TestDto ) ) return false ;
42 TestDto o = ( TestDto ) other ;
43 return ( id == null ? o . id == null : id . equals ( o . id ) ) &&
44 ( nm == null ? o . nm == null : nm . equals ( o . nm ) ) ;
45 }
46 @Override
47 public String toString ( ) {
48 return getClass ( ) . getSimpleName ( ) + "[id=" + id + ",nm=" + nm + "]" ;
49 }
50 }
init. : [TestDto[id=2,nm=b], null, TestDto[id=null,nm=c], TestDto[id=1,nm=a]]
sorted: [TestDto[id=1,nm=a], TestDto[id=2,nm=b], TestDto[id=null,nm=c], null]