From f1929f39dcf7af52fc0dd34c82af2ebec8e99280 Mon Sep 17 00:00:00 2001 From: EpicKnarvik97 Date: Fri, 8 May 2020 18:55:21 +0200 Subject: [PATCH] Makes a new utility class containing methods related to lists --- .../ffmpegconverter/utility/ListUtil.java | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 src/main/java/net/knarcraft/ffmpegconverter/utility/ListUtil.java diff --git a/src/main/java/net/knarcraft/ffmpegconverter/utility/ListUtil.java b/src/main/java/net/knarcraft/ffmpegconverter/utility/ListUtil.java new file mode 100644 index 0000000..8657e3e --- /dev/null +++ b/src/main/java/net/knarcraft/ffmpegconverter/utility/ListUtil.java @@ -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

The first array.

+ * @param listB

The second array.

+ * @param

The type of the two lists.

+ * @return

A new array containing all elements from the two arrays.

+ */ + static 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

The list to process.

+ * @param predicate

The predicate to test.

+ * @param

The type of the list.

+ * @return

A new list containing all matching elements.

+ */ + static List getMatching(List list, Predicate predicate) { + List 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 Anything which can be stored in a list + * @return True if at least one element fulfills the predicate + */ + static boolean listContains(T[] list, Predicate 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

A list of tokens.

+ * @param index

The index of the token containing comma separated entries.

+ * @return

A string list.

+ */ + public static String[] getList(List 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; + } +}