feat: add common used collection creation function to library

This commit is contained in:
金戟
2022-08-09 14:25:52 +08:00
parent 55a6e141fc
commit 9788dd9ecc
2 changed files with 80 additions and 2 deletions

View File

@@ -0,0 +1,33 @@
package com.alibaba.testable.core.model;
import java.io.Serializable;
/**
* @author flin
*/
public class Pair<L, R> implements Serializable {
private static final long serialVersionUID = -5197546316467446976L;
/** Left object */
private L left;
/** Right object */
private R right;
public Pair(L left, R right) {
this.left = left;
this.right = right;
}
public L getLeft() {
return left;
}
public R getRight() {
return right;
}
public static <L, R> Pair<L, R> of(L l, R r) {
return new Pair<L, R>(l, r);
}
}

View File

@@ -1,10 +1,14 @@
package com.alibaba.testable.core.util;
import java.util.Collection;
import java.util.Iterator;
import com.alibaba.testable.core.model.Pair;
import java.util.*;
public class CollectionUtil {
/**
* Get slice of args[pos, args.length]
*/
public static Object[] slice(Object[] args, int pos) {
int size = args.length - pos;
if (size <= 0) {
@@ -15,6 +19,9 @@ public class CollectionUtil {
return slicedArgs;
}
/**
* Join a collection to string
*/
public static String join(Collection<?> collection, String joinSymbol) {
StringBuilder sb = new StringBuilder();
for(Iterator<?> i = collection.iterator(); i.hasNext(); sb.append((String)i.next())) {
@@ -25,6 +32,9 @@ public class CollectionUtil {
return sb.toString();
}
/**
* Check whether target exist in collection
*/
public static <T> boolean contains(T[] collection, T target) {
for (T item : collection) {
if (target.equals(item)) {
@@ -33,4 +43,39 @@ public class CollectionUtil {
}
return false;
}
/**
* Create an array
*/
public static <T> T[] arrayOf(T... items) {
return items;
}
/**
* Create a list
*/
public static <T> List<T> listOf(T... items) {
return Arrays.asList(items);
}
/**
* Create a map
*/
public static <K, V> Map<K, V> mapOf(Pair<K, V>... pair) {
return mapOf(new HashMap<K, V>(pair.length), pair);
}
/**
* Create an ordered map
*/
public static <K, V> Map<K, V> orderMapOf(Pair<K, V>... pair) {
return mapOf(new LinkedHashMap<K, V>(pair.length), pair);
}
private static <K, V> Map<K, V> mapOf(Map<K, V> kvs, Pair<K, V>[] pair) {
for (Pair<K, V> p : pair) {
kvs.put(p.getLeft(), p.getRight());
}
return kvs;
}
}