回答編集履歴

2

nullsLastの使い方を間違えた

2018/11/17 05:48

投稿

swordone
swordone

スコア20651

test CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  private List<Method> getMethods(Class<?> cls) {
10
10
 
11
- return getMethods(cls, comparing(nullsLast(
11
+ return getMethods(cls, comparing(
12
12
 
13
13
  m -> Optional.ofNullable(m.getDeclaredAnnotation(Name.class))
14
14
 
@@ -18,7 +18,7 @@
18
18
 
19
19
  .orElse(null)
20
20
 
21
- )));
21
+ , nullsLast(naturalOrder())));
22
22
 
23
23
  }
24
24
 

1

コード

2018/11/17 05:48

投稿

swordone
swordone

スコア20651

test CHANGED
@@ -1 +1,39 @@
1
1
  引数にComparatorを取るようにして、そこに順番の定義を渡すようにすればいい。
2
+
3
+ 省略時はデフォルトのComparatorを使うことにすると
4
+
5
+ ```java
6
+
7
+ // import static java.util.Comparator.*;
8
+
9
+ private List<Method> getMethods(Class<?> cls) {
10
+
11
+ return getMethods(cls, comparing(nullsLast(
12
+
13
+ m -> Optional.ofNullable(m.getDeclaredAnnotation(Name.class))
14
+
15
+ .map(Name::value)
16
+
17
+ .filter(s -> s.length() != 0)
18
+
19
+ .orElse(null)
20
+
21
+ )));
22
+
23
+ }
24
+
25
+ private List<Method> getMethods(Class<?> cls, Comparator<? super Method> comparator) {
26
+
27
+ return Arrays.stream(cls.getDeclaredMethods())
28
+
29
+ .filter(method -> method.getName().startsWith("get"))
30
+
31
+ .filter(method -> method.getDeclaredAnnotation(Item.class) == null)
32
+
33
+ .sorted(comparator)
34
+
35
+ .collect(Collectors.toList());
36
+
37
+ }
38
+
39
+ ```