diff src/fschmidt/util/java/CollectionUtils.java @ 68:00520880ad02

add fschmidt source
author Franklin Schmidt <fschmidt@gmail.com>
date Sun, 05 Oct 2025 17:24:15 -0600
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/fschmidt/util/java/CollectionUtils.java	Sun Oct 05 17:24:15 2025 -0600
@@ -0,0 +1,78 @@
+package fschmidt.util.java;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Set;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+
+
+public final class CollectionUtils {
+	private CollectionUtils() {}  // never
+
+	public static <K,V> Map<K,V> optimizeMap(Map<K,V> map) {
+		switch( map.size() ) {
+		case 0:
+			return Collections.emptyMap();
+		case 1:
+			Map.Entry<K,V> entry = map.entrySet().iterator().next();
+			return Collections.singletonMap(entry.getKey(),entry.getValue());
+		default:
+			return new HashMap<K,V>(map);
+		}
+	}
+
+	public static <T> List<T> optimizeList(List<T> list) {
+		switch( list.size() ) {
+		case 0:
+			return Collections.emptyList();
+		case 1:
+			return Collections.singletonList(list.get(0));
+		default:
+			return new ArrayList<T>(list);
+		}
+	}
+
+	public static <T> Set<T> optimizeSet(Set<T> set) {
+		switch( set.size() ) {
+		case 0:
+			return Collections.emptySet();
+		case 1:
+			return Collections.singleton(set.iterator().next());
+		default:
+			return new HashSet<T>(set);
+		}
+	}
+
+	public static <T> Set<T> optimizeLinkedSet(Set<T> set) {
+		switch( set.size() ) {
+		case 0:
+			return Collections.emptySet();
+		case 1:
+			return Collections.singleton(set.iterator().next());
+		default:
+			return new LinkedHashSet<T>(set);
+		}
+	}
+
+	public static boolean intersects(Set set,Iterable col) {
+		for( Object obj : col ) {
+			if( set.contains(obj) )
+				return true;
+		}
+		return false;
+	}
+
+	public static boolean intersects(Set set,Object[] col) {
+		for( Object obj : col ) {
+			if( set.contains(obj) )
+				return true;
+		}
+		return false;
+	}
+
+}