Makes a new utility class containing methods related to lists

This commit is contained in:
Kristian Knarvik 2020-05-08 18:55:21 +02:00
parent ef426f74ac
commit f1929f39dc

View File

@ -0,0 +1,81 @@
package net.knarcraft.ffmpegconverter.utility;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
/**
* A class which helps with operations on lists
*/
public final class ListUtil {
private ListUtil() {
}
/**
* Combines two arrays to one
* @param listA <p>The first array.</p>
* @param listB <p>The second array.</p>
* @param <T> <p>The type of the two lists.</p>
* @return <p>A new array containing all elements from the two arrays.</p>
*/
static <T> T[] concatenate(T[] listA, T[] listB) {
int listALength = listA.length;
int listBLength = listB.length;
@SuppressWarnings("unchecked")
T[] resultList = (T[]) Array.newInstance(listA.getClass().getComponentType(), listALength + listBLength);
System.arraycopy(listA, 0, resultList, 0, listALength);
System.arraycopy(listB, 0, resultList, listALength, listBLength);
return resultList;
}
/**
* Gets all list items according to the predicate
* @param list <p>The list to process.</p>
* @param predicate <p>The predicate to test.</p>
* @param <T> <p>The type of the list.</p>
* @return <p>A new list containing all matching elements.</p>
*/
static <T> List<T> getMatching(List<T> list, Predicate<T> predicate) {
List<T> copy = new ArrayList<>(list);
list.removeIf(predicate);
copy.removeAll(list);
return copy;
}
/**
* Tests if any element in a list fulfills a condition.
*
* @param list The list to test against
* @param predicate A predicate to use on every element in the list
* @param <T> Anything which can be stored in a list
* @return True if at least one element fulfills the predicate
*/
static <T> boolean listContains(T[] list, Predicate<T> predicate) {
for (T item : list) {
if (predicate.test(item)) {
return true;
}
}
return false;
}
/**
* Gets a list from a comma separated string at index in list
* @param list <p>A list of tokens.</p>
* @param index <p>The index of the token containing comma separated entries.</p>
* @return <p>A string list.</p>
*/
public static String[] getList(List<String> list, int index) {
String[] result = null;
if (list.size() > index) {
if (list.get(index).contains(",")) {
result = list.get(index).split(",");
} else {
result = new String[]{list.get(index)};
}
}
return result;
}
}