01 30 seconds of java8
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, Math.min(cur + size, numbers.length)))
.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
计算数组中某个值出现的次数:
deepFlatten
数组扁平化:
difference
求两个数组中的差集,同时也可以演变成求两个数组的交集:
distinctValuesOfArray
求两个数组的并集并去重,见 union :
everyNth
返回数组中的每个第 n 个元素:
indexOf
查找数组中元素的索引,在不存在元素的情况下返回-1:
lastIndexOf
查找数组中元素的最后索引,在不存在元素的情况下返回-1:
filterNonUnique
筛选出数组中的非唯一值:
initializeArrayWithRange
初始化一个数组,该数组包含在指定范围内的数字,传入 start 和 end:
initializeArrayWithValues
使用指定的值初始化并填充数组:
intersection
返回两个数组的交集,difference 微调,和 similarity 作用大同小异:
nthElement
返回数组的第 n 个元素:
pick
从对象中选择与给定键对应的键值对:
sample
从数组中返回一个随机元素:
shuffle
数组乱序,使用洗牌算法:
sampleSize
从数组中获取 n 个随机元素,思路是先乱序再抽取 n 个元素:
similarity
返回出现在两个数组中的元素数组,见 intersection:
symmetricDifference
返回两个数组之间的差集:
union
返回两个数组的并集,见 distinctValuesOfArray :
without
筛选出具有指定值之一的数组的元素:
Maths
average
求数组平均值:
isEven
检查数字是否是偶数。这个方法使用按位运算符,0b1 是 1 的二进制表示。数字为偶数时,& 运算符将返回 0。例如,IsEven(4) 会转换成 100 & 001,结果将是 000。
generateRandomInt
生成一个介于 Integer.MIN_VALUE 和 Integer.MAX_VALUE 之间的随机数:
String
anagrams
一个字符串的所有可能排列组合:
isNumeric
检查字符串是否为数字:
reverseString
反转字符串:
splitLines
将多行字符串拆分为行数组:
stringToIntegers
将由空格分隔的数字字符串转换为 int 数组:
Enum
getEnumMap
将枚举转换为 Map,其中 key 是枚举名,value 是枚举本身:
IO
readFileAsString
将文件内容读入字符串:
getCurrentWorkingDirectoryPath
获取当前工作目录:
stackTraceAsString
将异常堆栈跟踪转换为字符串:
参考文章: 30 seconds of java8
最后更新于
这有帮助吗?