68
|
1 package fschmidt.util.java;
|
|
2
|
|
3 import java.util.Collection;
|
|
4 import java.util.Collections;
|
|
5 import java.util.Map;
|
|
6 import java.util.HashMap;
|
|
7 import java.util.List;
|
|
8 import java.util.ArrayList;
|
|
9 import java.util.Set;
|
|
10 import java.util.HashSet;
|
|
11 import java.util.LinkedHashSet;
|
|
12
|
|
13
|
|
14 public final class CollectionUtils {
|
|
15 private CollectionUtils() {} // never
|
|
16
|
|
17 public static <K,V> Map<K,V> optimizeMap(Map<K,V> map) {
|
|
18 switch( map.size() ) {
|
|
19 case 0:
|
|
20 return Collections.emptyMap();
|
|
21 case 1:
|
|
22 Map.Entry<K,V> entry = map.entrySet().iterator().next();
|
|
23 return Collections.singletonMap(entry.getKey(),entry.getValue());
|
|
24 default:
|
|
25 return new HashMap<K,V>(map);
|
|
26 }
|
|
27 }
|
|
28
|
|
29 public static <T> List<T> optimizeList(List<T> list) {
|
|
30 switch( list.size() ) {
|
|
31 case 0:
|
|
32 return Collections.emptyList();
|
|
33 case 1:
|
|
34 return Collections.singletonList(list.get(0));
|
|
35 default:
|
|
36 return new ArrayList<T>(list);
|
|
37 }
|
|
38 }
|
|
39
|
|
40 public static <T> Set<T> optimizeSet(Set<T> set) {
|
|
41 switch( set.size() ) {
|
|
42 case 0:
|
|
43 return Collections.emptySet();
|
|
44 case 1:
|
|
45 return Collections.singleton(set.iterator().next());
|
|
46 default:
|
|
47 return new HashSet<T>(set);
|
|
48 }
|
|
49 }
|
|
50
|
|
51 public static <T> Set<T> optimizeLinkedSet(Set<T> set) {
|
|
52 switch( set.size() ) {
|
|
53 case 0:
|
|
54 return Collections.emptySet();
|
|
55 case 1:
|
|
56 return Collections.singleton(set.iterator().next());
|
|
57 default:
|
|
58 return new LinkedHashSet<T>(set);
|
|
59 }
|
|
60 }
|
|
61
|
|
62 public static boolean intersects(Set set,Iterable col) {
|
|
63 for( Object obj : col ) {
|
|
64 if( set.contains(obj) )
|
|
65 return true;
|
|
66 }
|
|
67 return false;
|
|
68 }
|
|
69
|
|
70 public static boolean intersects(Set set,Object[] col) {
|
|
71 for( Object obj : col ) {
|
|
72 if( set.contains(obj) )
|
|
73 return true;
|
|
74 }
|
|
75 return false;
|
|
76 }
|
|
77
|
|
78 }
|