-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
CollectionsUtil.java
85 lines (75 loc) · 2.31 KB
/
CollectionsUtil.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package me.nallar.tickthreading.util;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import me.nallar.tickthreading.Log;
public enum CollectionsUtil {
;
public static final String defaultDelimiter = ",";
public static List<String> split(String input) {
return split(input, defaultDelimiter);
}
public static List<String> split(String input, String delimiter) {
if (input == null || input.isEmpty()) {
return Collections.emptyList();
}
return new ArrayList<String>(Arrays.asList(input.split(delimiter)));
}
public static List<?> toObjects(Iterable<String> stringIterable, Class type) {
Constructor<?> constructor;
try {
constructor = type.getConstructor(String.class);
} catch (NoSuchMethodException e) {
Log.severe("Failed to convert string list to " + type, e);
return Collections.emptyList();
}
List<Object> objects = new ArrayList<Object>();
for (String s : stringIterable) {
try {
objects.add(constructor.newInstance(s));
} catch (Exception e) {
Log.severe("Failed to convert string list to " + type + " with string " + s, e);
}
}
return objects;
}
public static String join(Iterable iterable) {
return join(iterable, defaultDelimiter);
}
public static String join(Iterable iterable, String delimiter) {
StringBuilder stringBuilder = new StringBuilder();
boolean join = false;
for (Object o : iterable) {
if (join) {
stringBuilder.append(delimiter);
}
stringBuilder.append(o);
join = true;
}
return stringBuilder.toString();
}
public static Collection<String> stringify(Iterable objects, Collection<String> strings) {
for (Object o : objects) {
strings.add(o.toString());
}
return strings;
}
public static String joinMap(Map<?, ?> map) {
if (map.size() == 0) {
return "";
}
StringBuilder stringBuilder = new StringBuilder();
boolean notFirst = false;
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (notFirst) {
stringBuilder.append(',');
}
stringBuilder.append(entry.getKey().toString()).append(':').append(entry.getValue().toString());
}
return stringBuilder.toString();
}
}