Very useful Java 8 snippet

Posted by jwadenpfuhl on Fri, 17 May 2019 05:34:10 +0200

This is from me Mucho Net Handwriting: Very useful Java 8 snippet , please keep the link for upload;)

Array (array related)

chunk

Divides an array into small arrays of a specific size.

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

Calculates the number of occurrences of a value in an array.

Use Arrays.stream().filter().count() to calculate the total number of values equal to the specified value.

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

deepFlatten

Flattened array.

Using recursive implementation, 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

Returns the difference between two arrays.

Create a collection from b and use Arrays.stream().filter() on a to preserve only values that are not included in 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

Filter out all values from an array where the comparator function does not return true.

The comparator for int is implemented using the IntbinaryPerator function.

Use Arrays.stream().filter() and Arrays.stream().noneMatch() to find the corresponding value.

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

Returns all the different values of the array.

Use Arrays.stream().distinct() to remove all duplicate values.

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

dropElements

Remove elements from the array until the passed function returns true.Returns the remaining elements of the array.

Iterate through the array using an array loop, deleting the first element of the array until the value returned by the function is true.Returns the remaining elements.

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

Returns a new array, removing n elements from the right.

Check if n is shorter than the given array and use Array.copyOfRange() to slice it or return an empty array.

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

Returns each nth element in the array.

Use IntStream.range().filter() to create a new array that contains each nth element of a given array.

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

Finds the index of an element in an array and returns -1 if no element exists.

Use IntStream.range().filter() to find the index of the elements in the array.

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

lastIndexOf

Finds the last index of the elements in the array and returns -1 if no elements exist.

Use IntStream.iterate().limit().filter() to find the index of the elements in the array.

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

Filter out non-unique values in the array.

Use Arrays.stream().filter() for arrays that contain only unique values.

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

flatten

Flatten the array.

Create a new array using 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

Flattens the array to the specified depth.

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

Grouping array elements according to a given function.

Grouping using 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

Returns all elements except the last one in the array.

Use Arrays.copyOfRange() to return all elements except the last one.

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

initializeArrayWithRange

Initializes an array containing numbers in a specified range, passing in start and end.

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

initializeArrayWithValues

Initializes and populates the array with the specified value.

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

intersection

Returns a list of elements that exist in both arrays.

Create a collection from step two, then use Arrays.stream().filter() on a to hold the values contained in 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

Returns 1 if the array is sorted in ascending order, -1 if the array is sorted in descending order, and 0 if it is not.

Calculates the sort direction of the first two elements.Iterate the arrays using a for loop and compare them in pairs.If the direction changes, 0 is returned.
If the last element is reached, the direction is returned.

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

Connect all elements of an array to a string and return the string.

Creates an array of specified indexes using IntStream.range.Then, use Stream.reduce to group the elements into strings.

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

Returns the nth element of the array.

Use Arrays.copyOfRange() takes precedence over an array containing the nth element.

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

Select the key-value pair from the object that corresponds to the given key.

Use Arrays.stream to filter all keys present in arr.Then, use Collectors.toMap to convert all keys to 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

Filters an array of objects based on conditions and also filters out unspecified keys.

Use Arrays.stream().filter() to filter the array based on the predicate fn to return an object whose condition is true.
For each filtered Map object, create a new Map with keys in it.Finally, the Map objects are collected into an array.

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

Returns a random element from an array.

Use Math.Randoman() to generate a random number, multiply it by the length of the array, and use Math.floor() to get the nearest integer. This method also works with strings.

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

sampleSize

Get n random elements by unique key from array to array size.

according to Fisher-Yates algorithm , use Array.copyOfRange() to get the first n elements.

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

Randomize the order of array values to return a new array.

according to Fisher-Yates algorithm Reorder the elements of the array.

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

Returns an array of elements that appear in both arrays.

Use Arrays.stream().filter() to remove, and then use Arrays.stream().anyMatch() to match the value of the second part.

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

The return value should be inserted into the lowest index in the array to maintain its sort order.

Check if the arrays are sorted in descending (loosely) order.Use IntStream.range().filter() to find the appropriate index into which the element should be inserted.

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

Returns the symmetric difference between two arrays.

Create a Set from each array and use Arrays.stream().filter() to keep values that are not included by other values.Finally, connect the two arrays and create a new one and return.

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

Returns all elements in the array except the first element.

If the length of the array is greater than 1, it returns Arrays.copyOfRange(1), otherwise it returns the entire array.

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

take

Returns an array with n elements deleted from the beginning.

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

takeRight

Returns an array with n elements removed from the end.

Use Arrays.copyOfRange() to create an array with N elements taken from the end.

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

union

Returns each element that exists in either of the two arrays once.

Create a Set with all values of a and b and convert it to an array.

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

Filters out elements of an array with one of the specified values.

Use Arrays.strean().filter() to create an array that excludes (uses!) all hits.

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

Creates an element array based on the position in the original array.

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

Given a valid array of attribute identifiers and values, returns the object that associates the attribute with the value.

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 (Math Related)

average

Returns the average of two or more numbers.

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

gcd

Calculates the greatest common divisor (gcd) of a series of numbers.

Use Arrays.stream().reduce() and GCD (using recursive formulas) to calculate the greatest common divisor of a set of numbers.

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

Calculates the lowest common multiple (LCM) of an array of numbers.

Use Arrays.stream().reduce() and the LCM formula (using recursion) to calculate the lowest common multiple of a number array.

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

Find the next power greater than or equal to that value.

This method uses the left shift operator to shift the value from 1 to the right.On the right, use the Integer.numberOfLeadingZeros method.
001 << 2 would be 100. 100 in decimal is equal to 4.

Integer.numberOfLeadingZeros gives the number of numeric leading zeros.For example, a call to Integer.numberOfLeadingZeros(3) would assign a value of 30.
This is because 3 is represented as 11 in binary.Since integers have 32 bits, 30 bits have 0 bits.The right side of the left shift operator becomes 32-30 = 2.
Move left 1, that is, 001 << 2 will be 100, and 100 in decimal will equal 4.

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

isEven

Check if the number is even.

This method uses a bitwise operator, 0b1 being a binary representation of 1.
Because Java 7 can write binary text by prefixing it with 0b or 0B.
When the number is even, the &operator returns 0.For example, IsEven(4) will result in 100 & 001, and &will result in 000.

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

isPowerOfTwo

Check that a value is a positive power of 2.

To understand how it works, let's assume we called IsPowerOfTwo(4).

When the value is greater than 0, the right side of the &operator is evaluated.

The result of (~value + 1) is equal to the value itself, ~100 + 001 => 011 + 001 => 100.

(value & value) results in value, 100 & 100 = > 100..

When the value is equal to the value, this will express the value as true.

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

generateRandomInt

Generates a random number between Integer.MIN_VALUE and Integer.MAX_VALUE.

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

String (string dependent)

anagrams

Generates all the characters of a string (including duplicates).

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

Returns the length of the string in bytes.

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

capitalize

Capitalize the first letter of the string.

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

Capitalize the first letter of each word in the string.

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

countVowels

Returns the number of vowels in the supplied string.

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

escapeRegExp

Escapes a string to be used in a regular expression.

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

fromCamelCase

Convert string from hump.

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

isAbsoluteUrl

Returns true if the given string is an absolute URL, false otherwise.

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

isLowerCase

Check that the string is lowercase.

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

isUpperCase

Check that the string is uppercase.

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

isPalindrome

Determines whether a string is palindromic.

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

isNumeric

Check that the string is a number.

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

mask

Replaces all characters except the last num with the specified mask character.

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

Reverse string.

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

sortCharactersInString

Arrange the characters in the string alphabetically.

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

splitLines

Split a multiline string into an array of rows.

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

toCamelCase

Convert a string to hump.

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

Convert the string to kebab case.

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

Regular matching.

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

Converts a string to snake lowercase, such as 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

Truncates the string to the specified length.

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

words

Converts a given string to an array of words.

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

stringToIntegers

Converts a space-delimited number string to an int array.

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

IO (IO Flow Related)

convertInputStreamToString

Converts InputStream to a string.

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

Reads the contents of the file into a string.

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

getCurrentWorkingDirectoryPath

Gets the current working directory.

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

tmpDirName

Returns the value of the java.io.tmpdir system property.If there is no separator at the end, the separator is appended.

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

    return tmpDirName;
}

Exception (abnormal correlation)

stackTraceAsString

Converts an exception stack trace to a string.

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

System

osName

Gets the name of the operating system as a lowercase string.

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

isDebuggerEnabled

Check that the JVM is in debug mode.

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

}

Class (class related)

getAllInterfaces

This method returns all interfaces implemented by a given class and its superclass.

This method works by connecting two Streams.The first Stream is built recursively by creating a stream with an interface and all interfaces implemented by the interface.
The second Stream is also true for superclasses.The result is to join the two Streams after deleting duplicates.

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

This method checks whether the specified class is an internal class or a static nested class.

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

Enum (enumeration related)

getEnumMap

Convert the enumeration to Map, where key is the enumeration name and value is the enumeration itself.

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()));
}

Topics: Java Attribute less jvm