1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.util;
20
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.List;
25
26
27
28
29 public class CollectionUtils {
30
31 private static final List<Object> EMPTY_LIST = Collections.unmodifiableList(
32 new ArrayList<Object>(0));
33
34
35 @SuppressWarnings("unchecked")
36 public static <T> Collection<T> nullSafe(Collection<T> in) {
37 if (in == null) {
38 return (Collection<T>)EMPTY_LIST;
39 }
40 return in;
41 }
42
43
44
45 public static <T> int nullSafeSize(Collection<T> collection) {
46 if (collection == null) {
47 return 0;
48 }
49 return collection.size();
50 }
51
52 public static <A, B> boolean nullSafeSameSize(Collection<A> a, Collection<B> b) {
53 return nullSafeSize(a) == nullSafeSize(b);
54 }
55
56
57
58 public static <T> boolean isEmpty(Collection<T> collection) {
59 return collection == null || collection.isEmpty();
60 }
61
62 public static <T> boolean notEmpty(Collection<T> collection) {
63 return !isEmpty(collection);
64 }
65
66
67
68 public static <T> T getFirst(Collection<T> collection) {
69 if (CollectionUtils.isEmpty(collection)) {
70 return null;
71 }
72 for (T t : collection) {
73 return t;
74 }
75 return null;
76 }
77
78
79
80
81
82 public static int getLastIndex(List<?> list){
83 if(isEmpty(list)){
84 return -1;
85 }
86 return list.size() - 1;
87 }
88
89
90
91
92
93
94 public static boolean isLastIndex(List<?> list, int index){
95 return index == getLastIndex(list);
96 }
97
98 public static <T> T getLast(List<T> list) {
99 if (isEmpty(list)) {
100 return null;
101 }
102 return list.get(list.size() - 1);
103 }
104 }