瀏覽代碼

增加工具类

zhouhao 7 年之前
父節點
當前提交
49b91ce5e5

+ 48 - 0
hsweb-commons/hsweb-commons-utils/src/main/java/org/hswebframework/web/Lists.java

@@ -0,0 +1,48 @@
+package org.hswebframework.web;
+
+import java.util.*;
+import java.util.function.Supplier;
+
+/**
+ * List工具,用于构建list等操作
+ *
+ * @author zhouhao
+ */
+public class Lists {
+
+    public static <V> ListBuilder<V> buildList(Supplier<List<V>> supplier) {
+        return buildList(supplier.get());
+    }
+
+    public static <V> ListBuilder<V> buildList(V... array) {
+        return buildList(array.length == 0 ? new ArrayList<>() : new ArrayList<>(Arrays.asList(array)));
+    }
+
+    public static <V> ListBuilder<V> buildList(List<V> target) {
+        return new ListBuilder<>(target);
+    }
+
+    public static class ListBuilder<V> {
+        private final List<V> target;
+
+        private ListBuilder(List<V> target) {
+            Objects.requireNonNull(target);
+            this.target = target;
+        }
+
+        public ListBuilder<V> add(V value) {
+            this.target.add(value);
+            return this;
+        }
+
+        public ListBuilder<V> addAll(Collection<V> value) {
+            this.target.addAll(value);
+            return this;
+        }
+
+        public List<V> get() {
+            return target;
+        }
+
+    }
+}

+ 54 - 0
hsweb-commons/hsweb-commons-utils/src/main/java/org/hswebframework/web/Maps.java

@@ -0,0 +1,54 @@
+package org.hswebframework.web;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Supplier;
+
+/**
+ * map工具类,用于构造map等操作
+ * <p>
+ * <pre>
+ *    Maps.<String, Object>buildMap()
+ *      .put("name", "age")
+ *      .put("age", 1)
+ *      .get()
+ * </pre>
+ *
+ * @author zhouhao
+ */
+public final class Maps {
+
+    private Maps() {
+    }
+
+    public static <K, V> MapBuilder<K, V> buildMap(Map<K, V> target) {
+        return new MapBuilder<>(target);
+    }
+
+    public static <K, V> MapBuilder<K, V> buildMap() {
+        return new MapBuilder<>(new HashMap<K, V>());
+    }
+
+    public static <K, V> MapBuilder<K, V> buildMap(Supplier<Map<K, V>> mapSupplier) {
+        return new MapBuilder<>(mapSupplier.get());
+    }
+
+    public static class MapBuilder<K, V> {
+        final Map<K, V> target;
+
+        private MapBuilder(Map<K, V> target) {
+            Objects.requireNonNull(target);
+            this.target = target;
+        }
+
+        public MapBuilder<K, V> put(K key, V value) {
+            this.target.put(key, value);
+            return this;
+        }
+
+        public Map<K, V> get() {
+            return target;
+        }
+    }
+}