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