非常實用的 Java 8 代碼片段

原文鏈接:https://www.imooc.com/u/4024769/articles

目錄

非常實用的 Java 8 代碼片段

Array(數組相關)

chunk

concat

countOccurrences

deepFlatten

difference

differenceWith

distinctValuesOfArray

dropElements

dropRight

everyNth

indexOf

lastIndexOf

filterNonUnique

flatten

flattenDepth

groupBy

initial

initializeArrayWithRange

initializeArrayWithValues

intersection

isSorted

join

nthElement

pick

reducedFilter

sample

sampleSize

shuffle

similarity

sortedIndex

symmetricDifference

tail

take

takeRight

union

without

zip

zipObject

Maths(數學相關)

average

gcd

lcm

findNextPositivePowerOfTwo

isEven

isPowerOfTwo

generateRandomInt

String(字符串相關)

anagrams

byteSize

capitalize

capitalizeEveryWord

countVowels

escapeRegExp

fromCamelCase

isAbsoluteUrl

isLowerCase

isUpperCase

isPalindrome

isNumeric

mask

reverseString

sortCharactersInString

splitLines

toCamelCase

toKebabCase

match

toSnakeCase

truncateString

words

stringToIntegers

IO(IO流相關)

convertInputStreamToString

readFileAsString

getCurrentWorkingDirectoryPath

tmpDirName

Exception(異常相關)

stackTraceAsString

System

osName

isDebuggerEnabled

Class(類相關)

getAllInterfaces

isInnerClass

Enum(枚舉相關)

getEnumMap


非常實用的 Java 8 代碼片段

Array(數組相關)

chunk

將數組分割成特定大小的小數組。

public static int[][] chunk(int[] numbers, int size) {
    return IntStream.iterate(0, i -> i + size)
            .limit((long) Math.ceil((double) numbers.length / size))
            .mapToObj(cur -> Arrays.copyOfRange(numbers, cur, cur + size > numbers.length ? numbers.length : cur + size))
            .toArray(int[][]::new);
}

concat

public static <T> T[] concat(T[] first, T[] second) {
    return Stream.concat(
            Stream.of(first),
            Stream.of(second)
    ).toArray(i -> (T[]) Arrays.copyOf(new Object[0], i, first.getClass()));
}

countOccurrences

計算數組中某個值出現的次數。

使用 Arrays.stream().filter().count() 計算等於指定值的值的總數。

public static long countOccurrences(int[] numbers, int value) {
    return Arrays.stream(numbers)
            .filter(number -> number == value)
            .count();
}

deepFlatten

數組扁平化。

使用遞歸實現,Arrays.stream().flatMapToInt()

public static int[] deepFlatten(Object[] input) {
    return Arrays.stream(input)
            .flatMapToInt(o -> {
                if (o instanceof Object[]) {
                    return Arrays.stream(deepFlatten((Object[]) o));
                }
                return IntStream.of((Integer) o);
            }).toArray();
}

difference

返回兩個數組之間的差異。

從 b 中創建一個集合,然後在 a 上使用 Arrays.stream().filter() 只保留 b 中不包含的值。

public static int[] difference(int[] first, int[] second) {
    Set<Integer> set = Arrays.stream(second).boxed().collect(Collectors.toSet());
    return Arrays.stream(first)
            .filter(v -> !set.contains(v))
            .toArray();
}

differenceWith

從比較器函數不返回true的數組中篩選出所有值。

int的比較器是使用IntbinaryPerator函數來實現的。

使用 Arrays.stream().filter() 和 Arrays.stream().noneMatch() 查找相應的值。

public static int[] differenceWith(int[] first, int[] second, IntBinaryOperator comparator) {
    return Arrays.stream(first)
            .filter(a ->
                    Arrays.stream(second)
                            .noneMatch(b -> comparator.applyAsInt(a, b) == 0)
            ).toArray();
}

distinctValuesOfArray

返回數組的所有不同值。

使用 Arrays.stream().distinct() 去除所有重複的值。

public static int[] distinctValuesOfArray(int[] elements) {
    return Arrays.stream(elements).distinct().toArray();
}

dropElements

移除數組中的元素,直到傳遞的函數返回true爲止。返回數組中的其餘元素。

使用數組循環遍歷數組,將數組的第一個元素刪除,直到函數返回的值爲真爲止。返回其餘的元素。

public static int[] dropElements(int[] elements, IntPredicate condition) {
    while (elements.length > 0 && !condition.test(elements[0])) {
        elements = Arrays.copyOfRange(elements, 1, elements.length);
    }
    return elements;
}

dropRight

返回一個新數組,從右邊移除n個元素。

檢查n是否短於給定的數組,並使用 Array.copyOfRange() 以便對其進行相應的切片或返回一個空數組。

public static int[] dropRight(int[] elements, int n) {
    if (n < 0) {
        throw new IllegalArgumentException("n is less than 0");
    }
    return n < elements.length
            ? Arrays.copyOfRange(elements, 0, elements.length - n)
            : new int[0];
}

everyNth

返回數組中的每個第n個元素。

使用 IntStream.range().filter() 創建一個新數組,該數組包含給定數組的每個第n個元素。

public static int[] everyNth(int[] elements, int nth) {
     return IntStream.range(0, elements.length)
             .filter(i -> i % nth == nth - 1)
             .map(i -> elements[i])
             .toArray();
 }

indexOf

查找數組中元素的索引,在不存在元素的情況下返回-1。

使用 IntStream.range().filter() 查找數組中元素的索引。

public static int indexOf(int[] elements, int el) {
    return IntStream.range(0, elements.length)
            .filter(idx -> elements[idx] == el)
            .findFirst()
            .orElse(-1);
}

lastIndexOf

查找數組中元素的最後索引,在不存在元素的情況下返回-1。

使用 IntStream.iterate().limit().filter() 查找數組中元素的索引。

public static int lastIndexOf(int[] elements, int el) {
    return IntStream.iterate(elements.length - 1, i -> i - 1)
            .limit(elements.length)
            .filter(idx -> elements[idx] == el)
            .findFirst()
            .orElse(-1);
}

filterNonUnique

篩選出數組中的非唯一值。

對只包含唯一值的數組使用 Arrays.stream().filter()

public static int[] filterNonUnique(int[] elements) {
    return Arrays.stream(elements)
            .filter(el -> indexOf(elements, el) == lastIndexOf(elements, el))
            .toArray();
}

flatten

使數組扁平。

使用 Arrays.stream().flatMapToInt().toArray() 創建一個新數組。

public static int[] flatten(Object[] elements) {
    return Arrays.stream(elements)
            .flatMapToInt(el -> el instanceof int[]
                    ? Arrays.stream((int[]) el)
                    : IntStream.of((int) el)
            ).toArray();
}

flattenDepth

將數組壓平到指定的深度。

public static Object[] flattenDepth(Object[] elements, int depth) {
    if (depth == 0) {
        return elements;
    }
    return Arrays.stream(elements)
            .flatMap(el -> el instanceof Object[]
                    ? Arrays.stream(flattenDepth((Object[]) el, depth - 1))
                    : Arrays.stream(new Object[]{el})
            ).toArray();


}

groupBy

根據給定函數對數組元素進行分組。

使用 Arrays.stream().collect(Collectors.groupingBy()) 分組。

public static <T, R> Map<R, List<T>> groupBy(T[] elements, Function<T, R> func) {
    return Arrays.stream(elements).collect(Collectors.groupingBy(func));
}

initial

返回數組中除去最後一個的所有元素。

使用 Arrays.copyOfRange() 返回除最後一個之外的所有元素。

public static <T> T[] initial(T[] elements) {
    return Arrays.copyOfRange(elements, 0, elements.length - 1);
}

initializeArrayWithRange

初始化一個數組,該數組包含在指定範圍內的數字,傳入 start 和 end

public static int[] initializeArrayWithRange(int end, int start) {
    return IntStream.rangeClosed(start, end).toArray();
}

initializeArrayWithValues

使用指定的值初始化並填充數組。

public static int[] initializeArrayWithValues(int n, int value) {
    return IntStream.generate(() -> value).limit(n).toArray();
}

intersection

返回兩個數組中存在的元素列表。

從第二步創建一個集合,然後在 a 上使用 Arrays.stream().filter() 來保存包含在 b 中的值。

public static int[] intersection(int[] first, int[] second) {
    Set<Integer> set = Arrays.stream(second).boxed().collect(Collectors.toSet());
    return Arrays.stream(first)
            .filter(set::contains)
            .toArray();
}

isSorted

如果數組按升序排序,則返回 1,如果數組按降序排序,返回 -1,如果沒有排序,則返回 0

計算前兩個元素的排序 direction。使用for循環對數組進行迭代,並對它們進行成對比較。如果 direction 發生變化,則返回 0
如果到達最後一個元素,則返回 direction

public static <T extends Comparable<? super T>> int isSorted(T[] arr) {
    final int direction = arr[0].compareTo(arr[1]) < 0 ? 1 : -1;
    for (int i = 0; i < arr.length; i++) {
        T val = arr[i];
        if (i == arr.length - 1) return direction;
        else if ((val.compareTo(arr[i + 1]) * direction > 0)) return 0;
    }
    return direction;
}

join

將數組的所有元素連接到字符串中,並返回此字符串。

使用 IntStream.range 創建一個指定索引的數組。然後,使用 Stream.reduce 將元素組合成字符串。

public static <T> String join(T[] arr, String separator, String end) {
    return IntStream.range(0, arr.length)
            .mapToObj(i -> new SimpleEntry<>(i, arr[i]))
            .reduce("", (acc, val) -> val.getKey() == arr.length - 2
                    ? acc + val.getValue() + end
                    : val.getKey() == arr.length - 1 ? acc + val.getValue() : acc + val.getValue() + separator, (fst, snd) -> fst);
}

nthElement

返回數組的第n個元素。

Use Arrays.copyOfRange() 優先得到包含第n個元素的數組。

public static <T> T nthElement(T[] arr, int n) {
    if (n > 0) {
        return Arrays.copyOfRange(arr, n, arr.length)[0];
    }
    return Arrays.copyOfRange(arr, arr.length + n, arr.length)[0];
}

pick

從對象中選擇與給定鍵對應的鍵值對。

使用 Arrays.stream 過濾 arr 中存在的所有鍵。然後,使用 Collectors.toMap 將所有的key轉換爲Map。

public static <T, R> Map<T, R> pick(Map<T, R> obj, T[] arr) {
    return Arrays.stream(arr)
            .filter(obj::containsKey)
            .collect(Collectors.toMap(k -> k, obj::get));
}

reducedFilter

根據條件篩選對象數組,同時篩選出未指定的鍵。

使用 Arrays.stream().filter() 根據謂詞 fn 過濾數組,以便返回條件爲真的對象。
對於每個過濾的Map對象,創建一個新的Map,其中包含 keys 中的鍵。最後,將Map對象收集到一個數組中。

public static Map<String, Object>[] reducedFilter(Map<String, Object>[] data, String[] keys, Predicate<Map<String, Object>> fn) {
    return Arrays.stream(data)
            .filter(fn)
            .map(el -> Arrays.stream(keys).filter(el::containsKey)
                    .collect(Collectors.toMap(Function.identity(), el::get)))
            .toArray((IntFunction<Map<String, Object>[]>) Map[]::new);
}

sample

從數組中返回一個隨機元素。

使用 Math.Randoman() 生成一個隨機數,然後將它乘以數組的 length,然後使用 Math.floor() 獲得一個最近的整數,該方法也適用於字符串。

public static <T> T sample(T[] arr) {
    return arr[(int) Math.floor(Math.random() * arr.length)];
}

sampleSize

從 array 到 array 大小的唯一鍵獲取 n 個隨機元素。

根據Fisher-Yates算法,使用 Array.copyOfRange() 獲得優先的 n 個元素。

public static <T> T[] sampleSize(T[] input, int n) {
    T[] arr = Arrays.copyOf(input, input.length);
    int length = arr.length;
    int m = length;
    while (m > 0) {
        int i = (int) Math.floor(Math.random() * m--);
        T tmp = arr[i];
        arr[i] = arr[m];
        arr[m] = tmp;
    }
    return Arrays.copyOfRange(arr, 0, n > length ? length : n);
}

shuffle

將數組值的順序隨機化,返回一個新數組。

根據 Fisher-Yates 算法 重新排序數組的元素。

public static <T> T[] shuffle(T[] input) {
    T[] arr = Arrays.copyOf(input, input.length);
    int length = arr.length;
    int m = length;
    while (m > 0) {
        int i = (int) Math.floor(Math.random() * m--);
        T tmp = arr[i];
        arr[i] = arr[m];
        arr[m] = tmp;
    }
    return arr;
}

similarity

返回出現在兩個數組中的元素數組。

使用 Arrays.stream().filter() 移除,然後使用 Arrays.stream().anyMatch() 匹配 second 部分的值。

public static <T> T[] similarity(T[] first, T[] second) {
    return Arrays.stream(first)
            .filter(a -> Arrays.stream(second).anyMatch(b -> Objects.equals(a, b)))
            // Make a new array of first's runtime type, but empty content:
            .toArray(i -> (T[]) Arrays.copyOf(new Object[0], i, first.getClass()));
}

sortedIndex

返回值應該插入到數組中的最低索引,以保持其排序順序。

檢查數組是否按降序(鬆散地)排序。 使用 IntStream.range().filter() 來找到元素應該被插入的合適的索引。

public static <T extends Comparable<? super T>> int sortedIndex(T[] arr, T el) {
    boolean isDescending = arr[0].compareTo(arr[arr.length - 1]) > 0;
    return IntStream.range(0, arr.length)
            .filter(i -> isDescending ? el.compareTo(arr[i]) >= 0 : el.compareTo(arr[i]) <= 0)
            .findFirst()
            .orElse(arr.length);
}

symmetricDifference

返回兩個數組之間的對稱差異。

從每個數組中創建一個 Set,然後使用 Arrays.stream().filter() 來保持其他值不包含的值。最後,連接兩個數組並創建一個新數組並返回。

public static <T> T[] symmetricDifference(T[] first, T[] second) {
    Set<T> sA = new HashSet<>(Arrays.asList(first));
    Set<T> sB = new HashSet<>(Arrays.asList(second));

    return Stream.concat(
            Arrays.stream(first).filter(a -> !sB.contains(a)),
            Arrays.stream(second).filter(b -> !sA.contains(b))
    ).toArray(i -> (T[]) Arrays.copyOf(new Object[0], i, first.getClass()));
}

tail

返回數組中除第一個元素外的所有元素。

如果數組的長度大於1,則返回 Arrays.copyOfRange(1),否則返回整個數組。

public static <T> T[] tail(T[] arr) {
    return arr.length > 1
            ? Arrays.copyOfRange(arr, 1, arr.length)
            : arr;
}

take

返回一個從開頭刪除n個元素的數組。

public static <T> T[] take(T[] arr, int n) {
    return Arrays.copyOfRange(arr, 0, n);
}

takeRight

返回從末尾移除n個元素的數組。

使用 Arrays.copyOfRange() 用從末尾取來的 N 個元素來創建一個數組。

public static <T> T[] takeRight(T[] arr, int n) {
    return Arrays.copyOfRange(arr, arr.length - n, arr.length);
}

union

返回兩個數組中任何一箇中存在的每個元素一次。

使用 a 和 b 的所有值創建一個 Set,並將其轉換爲數組。

public static <T> T[] union(T[] first, T[] second) {
    Set<T> set = new HashSet<>(Arrays.asList(first));
    set.addAll(Arrays.asList(second));
    return set.toArray((T[]) Arrays.copyOf(new Object[0], 0, first.getClass()));
}

without

篩選出具有指定值之一的數組的元素。

使用 Arrays.strean().filter() 創建一個數組,排除(使用 !Arrays.asList(elements).contains())所有命中的值。

public static <T> T[] without(T[] arr, T... elements) {
    List<T> excludeElements = Arrays.asList(elements);
    return Arrays.stream(arr)
            .filter(el -> !excludeElements.contains(el))
            .toArray(i -> (T[]) Arrays.copyOf(new Object[0], i, arr.getClass()));
}

zip

根據原始數組中的位置創建元素數組。

public static List<Object[]> zip(Object[]... arrays) {
    OptionalInt max = Arrays.stream(arrays).mapToInt(arr -> arr.length).max();
    return IntStream.range(0, max.getAsInt())
            .mapToObj(i -> Arrays.stream(arrays)
                    .map(arr -> i < arr.length ? arr[i] : null)
                    .toArray())
            .collect(Collectors.toList());
}

zipObject

給定有效的屬性標識符數組和值數組,返回將屬性與值關聯的對象。

public static Map<String, Object> zipObject(String[] props, Object[] values) {
    return IntStream.range(0, props.length)
            .mapToObj(i -> new SimpleEntry<>(props[i], i < values.length ? values[i] : null))
            .collect(
                    HashMap::new, (m, v) -> m.put(v.getKey(), v.getValue()), HashMap::putAll);
}

Maths(數學相關)

average

返回兩個或兩個以上數字的平均值。

public static double average(int[] arr) {
    return IntStream.of(arr)
            .average()
            .orElseThrow(() -> new IllegalArgumentException("Array is empty"));
}

gcd

計算一系列數字的最大公約數(gcd)。

使用 Arrays.stream().reduce() 和 GCD(使用遞歸公式)計算一組數字的最大公約數。

public static OptionalInt gcd(int[] numbers) {
    return Arrays.stream(numbers)
            .reduce((a, b) -> gcd(a, b));
}

private static int gcd(int a, int b) {
    if (b == 0) {
        return a;
    }
    return gcd(b, a % b);
}

lcm

計算數字數組的最低公共倍數(LCM)。

使用 Arrays.stream().reduce() 和 LCM公式(使用遞歸)來計算數字數組的最低公共倍數。

public static OptionalInt lcm(int[] numbers) {
    IntBinaryOperator lcm = (x, y) -> (x * y) / gcd(x, y);
    return Arrays.stream(numbers)
            .reduce((a, b) -> lcm.applyAsInt(a, b));
}

private static int gcd(int a, int b) {
    if (b == 0) {
        return a;
    }
    return gcd(b, a % b);
}

findNextPositivePowerOfTwo

查找大於或等於該值的下一個冪。

該方法使用左移運算符將1與右側的值位移。右側使用 Integer.numberOfLeadingZeros方法。
001 << 2 would be 100100 in decimal is equal to 4.

Integer.numberOfLeadingZeros 給出了數值前導零的數目。例如,調用 Integer.numberOfLeadingZeros(3) 將賦值爲30。
這是因爲3在二進制中表示爲 11。由於整數有32位,所以有30位有0位。左移運算符的右邊變爲 32-30 = 2
左移1,即 001 << 2 將是 100,十進制中的 100 等於 4

public static int findNextPositivePowerOfTwo(int value) {
    return 1 << (32 - Integer.numberOfLeadingZeros(value - 1));
}

isEven

檢查數字是否是偶數。

這個方法使用按位運算符,0b1 是1的二進制表示。
因爲Java 7可以通過用 0b 或 0B 作爲前綴來編寫二進制文字。
數字爲偶數時, 運算符將返回0。 例如,IsEven(4) 會導致 100 & 001 的結果將是 000

public static boolean isEven(final int value) {
    return (value & 0b1) == 0;
}

isPowerOfTwo

檢查一個值是2的正冪。

爲了理解它是如何工作的,讓我們假設我們調用了 IsPowerOfTwo(4)

當值大於0時,將評估 && 運算符的右側。

(~value + 1) 的結果等於值本身,~100 + 001 => 011 + 001 => 100

(value & value) 的結果是value,100 & 100 => 100.。

當值等於值時,這將把值表達爲真值。

public static boolean isPowerOfTwo(final int value) {
    return value > 0 && ((value & (~value + 1)) == value);
}

generateRandomInt

生成一個介於 Integer.MIN_VALUE 和 Integer.MAX_VALUE 之間的隨機數。

public static int generateRandomInt() {
    return ThreadLocalRandom.current().nextInt();
}

String(字符串相關)

anagrams

生成一個字符串的所有字符(包含重複)。

public static List<String> anagrams(String input) {
    if (input.length() <= 2) {
        return input.length() == 2
                ? Arrays.asList(input, input.substring(1) + input.substring(0, 1))
                : Collections.singletonList(input);
    }
    return IntStream.range(0, input.length())
            .mapToObj(i -> new SimpleEntry<>(i, input.substring(i, i + 1)))
            .flatMap(entry ->
                    anagrams(input.substring(0, entry.getKey()) + input.substring(entry.getKey() + 1))
                            .stream()
                            .map(s -> entry.getValue() + s))
            .collect(Collectors.toList());
}

byteSize

以字節爲單位返回字符串的長度。

public static int byteSize(String input) {
    return input.getBytes().length;
}

capitalize

將字符串首字母大寫。

public static String capitalize(String input, boolean lowerRest) {
    return input.substring(0, 1).toUpperCase() +
            (lowerRest
                    ? input.substring(1, input.length()).toLowerCase()
                    : input.substring(1, input.length()));
}

capitalizeEveryWord

將字符串中每個單詞的首字母大寫。

public static String capitalizeEveryWord(final String input) {
    return Pattern.compile("\\b(?=\\w)").splitAsStream(input)
            .map(w -> capitalize(w, false))
            .collect(Collectors.joining());
}

countVowels

在提供的字符串中返回元音的個數。

public static int countVowels(String input) {
    return input.replaceAll("[^aeiouAEIOU]", "").length();
}

escapeRegExp

轉義要在正則表達式中使用的字符串。

public static String escapeRegExp(String input) {
    return Pattern.quote(input);
}

fromCamelCase

從駝峯式轉換字符串。

public static String fromCamelCase(String input, String separator) {
    return input
            .replaceAll("([a-z\\d])([A-Z])", "$1" + separator + "$2")
            .toLowerCase();
}

isAbsoluteUrl

如果給定的字符串是絕對URL,則返回 true,否則返回 false

public static boolean isAbsoluteUrl(String url) {
    return Pattern.compile("^[a-z][a-z0-9+.-]*:").matcher(url).find();
}

isLowerCase

檢查字符串是否爲小寫。

public static boolean isLowerCase(String input) {
    return Objects.equals(input, input.toLowerCase());
}

isUpperCase

檢查字符串是否爲大寫。

public static boolean isUpperCase(String input) {
    return Objects.equals(input, input.toUpperCase());
}

isPalindrome

判斷一個字符串是否迴文。

public static boolean isPalindrome(String input) {
    String s = input.toLowerCase().replaceAll("[\\W_]", "");
    return Objects.equals(
            s,
            new StringBuilder(s).reverse().toString()
    );
}

isNumeric

檢查字符串是否爲數字。

public static boolean isNumeric(final String input) {
    return IntStream.range(0, input.length())
            .allMatch(i -> Character.isDigit(input.charAt(i)));
}

mask

用指定的掩碼字符替換除最後 num 個字符以外的所有字符。

public static String mask(String input, int num, String mask) {
    int length = input.length();
    return num > 0
            ?
            input.substring(0, length - num).replaceAll(".", mask)
                    + input.substring(length - num)
            :
            input.substring(0, Math.negateExact(num))
                    + input.substring(Math.negateExact(num), length).replaceAll(".", mask);
}

reverseString

反轉字符串。

public static String reverseString(String input) {
    return new StringBuilder(input).reverse().toString();
}

sortCharactersInString

按字母順序排列字符串中的字符。

public static String sortCharactersInString(String input) {
    return Arrays.stream(input.split("")).sorted().collect(Collectors.joining());
}

splitLines

將多行字符串拆分爲行數組。

public static String[] splitLines(String input) {
    return input.split("\\r?\\n");
}

toCamelCase

轉換一個字符串爲駝峯式。

public static String toCamelCase(String input) {
    Matcher matcher = Pattern.compile("[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+").matcher(input);
    List<String> matchedParts = new ArrayList<>();
    while (matcher.find()) {
        matchedParts.add(matcher.group(0));
    }
    String s = matchedParts.stream()
            .map(x -> x.substring(0, 1).toUpperCase() + x.substring(1).toLowerCase())
            .collect(Collectors.joining());
    return s.substring(0, 1).toLowerCase() + s.substring(1);
}

toKebabCase

將字符串轉換爲kebab大小寫。

public static String toKebabCase(String input) {
    Matcher matcher = Pattern.compile("[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+").matcher(input);
    List<String> matchedParts = new ArrayList<>();
    while (matcher.find()) {
        matchedParts.add(matcher.group(0));
    }
    return matchedParts.stream()
            .map(String::toLowerCase)
            .collect(Collectors.joining("-"));
}

match

正則匹配。

public static List<String> match(String input, String regex) {
    Matcher matcher = Pattern.compile(regex).matcher(input);
    List<String> matchedParts = new ArrayList<>();
    while (matcher.find()) {
        matchedParts.add(matcher.group(0));
    }
    return matchedParts;
}

toSnakeCase

將字符串轉換爲蛇形小寫,如 Im_Biezhi

public static String toSnakeCase(String input) {
    Matcher matcher = Pattern.compile("[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+").matcher(input);
    List<String> matchedParts = new ArrayList<>();
    while (matcher.find()) {
        matchedParts.add(matcher.group(0));
    }
    return matchedParts.stream()
            .map(String::toLowerCase)
            .collect(Collectors.joining("_"));
}

truncateString

將字符串截斷到指定的長度。

public static String truncateString(String input, int num) {
    return input.length() > num
            ? input.substring(0, num > 3 ? num - 3 : num) + "..."
            : input;
}

words

將給定的字符串轉換爲單詞數組。

public static String[] words(String input) {
    return Arrays.stream(input.split("[^a-zA-Z-]+"))
            .filter(s -> !s.isEmpty())
            .toArray(String[]::new);
}

stringToIntegers

將由空格分隔的數字字符串轉換爲 int 數組。

public static int[] stringToIntegers(String numbers) {
        return Arrays.stream(numbers.split(" ")).mapToInt(Integer::parseInt).toArray();
}

IO(IO流相關)

convertInputStreamToString

將InputStream轉換爲字符串。

public static String convertInputStreamToString(final InputStream in) throws IOException {
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length;
    while ((length = in.read(buffer)) != -1) {
        result.write(buffer, 0, length);
    }
    return result.toString(StandardCharsets.UTF_8.name());
}

readFileAsString

將文件內容讀入字符串。

public String readFileAsString(Path path) throws IOException {
    return new String(Files.readAllBytes(path));
}

getCurrentWorkingDirectoryPath

獲取當前工作目錄。

public static String getCurrentWorkingDirectoryPath() {
    return FileSystems.getDefault().getPath("").toAbsolutePath().toString();
}

tmpDirName

返回 java.io.tmpdir 系統屬性的值。如果末尾沒有分隔符,則追加分隔符。

public static String tmpDirName() {
    String tmpDirName = System.getProperty("java.io.tmpdir");
    if (!tmpDirName.endsWith(File.separator)) {
        tmpDirName += File.separator;
    }

    return tmpDirName;
}

Exception(異常相關)

stackTraceAsString

將異常堆棧跟蹤轉換爲字符串。

public static String stackTraceAsString(final Throwable throwable) {
    final StringWriter sw = new StringWriter();
    throwable.printStackTrace(new PrintWriter(sw));
    return sw.toString();
}

System

osName

以小寫字符串的形式獲取操作系統的名稱。

public static String osName() {
    return System.getProperty("os.name").toLowerCase();
}

isDebuggerEnabled

檢查JVM是否爲debug模式。

public static boolean isDebuggerAttached() {
    final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    return runtimeMXBean.getInputArguments()
            .stream()
            .anyMatch(arg -> arg.contains("-agentlib:jdwp"));

}

Class(類相關)

getAllInterfaces

此方法返回由給定類及其超類實現的所有接口。

該方法通過連接兩個Stream來工作。第一個Stream是通過創建帶有接口的流和接口實現的所有接口來遞歸構建的。
第二個Stream對超類也是如此。其結果是刪除重複項後將兩個Stream連接起來。

public static List<Class<?>> getAllInterfaces(Class<?> cls) {
    return Stream.concat(
            Arrays.stream(cls.getInterfaces()).flatMap(intf ->
                    Stream.concat(Stream.of(intf), getAllInterfaces(intf).stream())),
            cls.getSuperclass() == null ? Stream.empty() : getAllInterfaces(cls.getSuperclass()).stream()
    ).distinct().collect(Collectors.toList());
}

isInnerClass

此方法檢查指定的類是內部類還是靜態嵌套類。

public static boolean isInnerClass(final Class<?> cls) {
    return cls != null && cls.getEnclosingClass() != null;
}

Enum(枚舉相關)

getEnumMap

將枚舉轉換爲 Map,其中 key 是枚舉名,value 是枚舉本身。

public static <E extends Enum<E>> Map<String, E> getEnumMap(final Class<E> enumClass) {
    return Arrays.stream(enumClass.getEnumConstants())
            .collect(Collectors.toMap(Enum::name, Function.identity()));
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章