1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.common.util;
17
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.List;
23 import java.util.Set;
24 import java.util.TreeSet;
25
26 import org.apache.commons.lang3.StringUtils;
27
28 public class CollectionUtils {
29
30
31
32
33 public static final <T> List<T> toEmptyList(T o) {
34 if (o == null) {
35 return Collections.<T> emptyList();
36 } else {
37 return Collections.singletonList(o);
38 }
39 }
40
41
42
43
44 public static final <T> List<T> toEmpty(List<T> list) {
45 if (list == null) {
46 return Collections.<T> emptyList();
47 } else {
48 return list;
49 }
50 }
51
52 public static final <T> List<T> toNullIfEmpty(List<T> list) {
53 if (isEmpty(list)) {
54 return null;
55 } else {
56 return list;
57 }
58 }
59
60 public static final <T> Collection<T> toNullIfEmpty(Collection<T> c) {
61 if (isEmpty(c)) {
62 return null;
63 } else {
64 return c;
65 }
66 }
67
68 public static final <T> List<T> getPreFilledList(int size, T value) {
69 if (value == null || size < 1) {
70 return Collections.<T> emptyList();
71 } else {
72 List<T> list = new ArrayList<T>(size);
73 for (int i = 0; i < size; i++) {
74 list.add(value);
75 }
76 return list;
77 }
78 }
79
80 public static final Object[] toObjectArray(List<Object> objects) {
81 return objects.toArray(new Object[objects.size()]);
82 }
83
84 public static final String[] toStringArray(List<String> strings) {
85 return strings.toArray(new String[strings.size()]);
86 }
87
88 public static final boolean isEmpty(Collection<?> c) {
89 return c == null || c.size() == 0;
90 }
91
92 public static final List<String> sortedMerge(List<String> list, String csv) {
93 Set<String> set = new TreeSet<String>();
94 for (String string : toEmpty(list)) {
95 set.add(string);
96 }
97 for (String string : getTrimmedListFromCSV(csv)) {
98 set.add(string);
99 }
100 return new ArrayList<String>(set);
101 }
102
103 public static final List<String> getTrimmedListFromCSV(String csv) {
104 if (StringUtils.isBlank(csv)) {
105 return Collections.<String> emptyList();
106 }
107 List<String> list = new ArrayList<String>();
108 String[] tokens = Str.splitAndTrimCSV(csv);
109 list.addAll(Arrays.asList(tokens));
110 return list;
111 }
112 }