您可以快速理解的有用的小Java 8功能的策划集合。
chunkcountOccurrencesdeepFlattendifferencedifferenceWithdistinctValuesOfArraydropElementsdropRighteveryNthfilterNonUniqueflattenflattenDepthgroupByheadinitialinitializeArrayWithRangeinitializeArrayWithValuesintersectionisSortedjoinnthElementpickreducedFilterremovesamplesampleSizeshufflesimilaritysortedIndexsymmetricDifferencetailtaketakeRightunionwithoutzipzipObjectaveragegcdlcmfindNextPositivePowerOfTwoisEvenisPowerOfTwogenerateRandomIntanagramsbyteSizecapitalizecapitalizeEveryWordcountVowelsescapeRegExpfromCamelCaseisAbsoluteURLisLowerCaseisUpperCaseisPalindromeisNumericmaskreverseStringsortCharactersInStringsplitLinestoCamelCasetoKebabCasematchtoSnakeCasetruncateStringwordsstringToIntegersconvertInputStreamToStringreadFileAsStringgetCurrentWorkingDirectoryPathtmpDirNamestackTraceAsStringosNameisDebuggerEnabledgetAllInterfacesIsInnerClassgetEnumMap块将一个数组分成指定尺寸的较小阵列。
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 );
} 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 ()));
}计算数组中值的出现。
使用arrays.stream()。filter()。count()来计算等于指定值的值的总数。
public static long countOccurrences ( int [] numbers , int value ) {
return Arrays . stream ( numbers )
. filter ( number -> number == value )
. count ();
}深层变平阵列。
使用递归。使用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 ();
}返回两个阵列之间的差异。
从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 ();
}过滤从比较器函数不返回true的数组中的所有值。
使用IntbinaryOperator函数实现INT的比较器。
使用arrays.stream()。滤波器和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 ();
}返回数组的所有不同值。
使用Arrays.Stream()。dintict()丢弃所有重复的值。
public static int [] distinctValuesOfArray ( int [] elements ) {
return Arrays . stream ( elements ). distinct (). toArray ();
}删除数组中的元素,直到传递的功能返回true。返回数组中的其余元素。
使用arrays.copyofrange()循环穿过数组,以删除数组的第一个元素,直到函数返回的值为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 ;
}返回一个新数组,从右侧删除了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 ];
}返回数组中的每个元素。
使用intstream.range()。filter()创建一个新数组,其中包含给定数组的每个元素。
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 ();
}在数组中查找元素的索引。如果元素不存在,返回-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 );
}在数组中查找元素的最后索引。如果元素不存在,返回-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 );
}滤除数组中的非唯一值。
将Arrays.Stream()。filter()用于仅包含唯一值的数组。
public static int [] filterNonUnique ( int [] elements ) {
return Arrays . stream ( elements )
. filter ( el -> indexOf ( elements , el ) == lastIndexOf ( elements , el ))
. toArray ();
}变平阵列。
使用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 ();
}将阵列弄平到指定的深度。
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 ();
}根据给定函数分组数组的元素。
使用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 ));
}返回除最后一个元素的所有元素。使用arrays.copyofrange()返回所有除最后一个
public static < T > T [] initial ( T [] elements ) {
return Arrays . copyOfRange ( elements , 0 , elements . length - 1 );
}初始化包含指定范围内的数字的数组,其中起始和端是包容性的。
public static int [] initializeArrayWithRange ( int end , int start ) {
return IntStream . rangeClosed ( start , end ). toArray ();
}初始化并用指定值填充数组。
public static int [] initializeArrayWithValues ( int n , int value ) {
return IntStream . generate (() -> value ). limit ( n ). toArray ();
}返回两个数组中存在的元素列表。
创建一个集合,然后在a上使用arrays.stream.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 ();
}返回1如果数组按上升顺序排序,则-1如果以降序排序,则如果未排序为0 。
计算前两个元素的排序direction 。使用循环以迭代阵列项目并成对比较它们。如果direction变化,则返回0,如果达到最后一个元素, direction返回0 。
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 ;
}将数组的所有元素连接到字符串中,然后返回此字符串。使用分离器和端分离器。
使用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 );
}返回数组的第n个元素。
首先,使用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 ];
}选择与对象的给定键相对应的键值对。
使用Arrays.stream过滤arr中存在的所有键。然后,使用Collectors.toMap将所有键的键转换为地图。
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 ));
}根据条件过滤一个对象数组,同时还过滤未指定的密钥。
使用Arrays.stream().filter()根据谓词fn过滤数组,以便它返回条件为真的对象。对于每个过滤的地图对象,创建一个新的地图,其中包含keys中存在的键。最后,将所有地图对象收集到数组中。
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 );
}从数组返回一个随机元素。
使用Math.random()生成一个随机数,将其乘以length ,然后使用Math.floor()将其围成最接近的整数。该方法还可以与字符串一起使用。
public static < T > T sample ( T [] arr ) {
return arr [( int ) Math . floor ( Math . random () * arr . length )];
}从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 );
}随机返回新数组的数组值的顺序。
使用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 ;
}返回两个数组中出现的一系列元素。
使用Arrays.stream().filter()删除不属于second的值,使用Arrays.stream().anyMatch()确定。
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 ()));
}返回应将值插入数组的最低索引以维护其排序顺序。
检查阵列是否按降序排序(松散)。使用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 );
}返回两个阵列之间的对称差异。
从每个数组创建一个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 ()));
}返回数组中的所有元素,除了第一个元素。
返回Arrays.copyOfRange(1)如果阵列的length大于1 ,则返回整个数组。
public static < T > T [] tail ( T [] arr ) {
return arr . length > 1
? Arrays . copyOfRange ( arr , 1 , arr . length )
: arr ;
}从一开始就返回带有n个元素的数组。
public static < T > T [] take ( T [] arr , int n ) {
return Arrays . copyOfRange ( arr , 0 , n );
}从末端返回带有n个元素的数组。
使用Arrays.copyOfRange()创建数组的切片,其中n元素从末端获取。
public static < T > T [] takeRight ( T [] arr , int n ) {
return Arrays . copyOfRange ( arr , arr . length - n , arr . length );
}返回两个数组中任何一个中存在的每个元素。
创建一个具有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 ()));
}滤除具有指定值之一的数组的元素。
使用Arrays.strean().filter()创建一个数组排除(used !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 ()));
}创建一系列元素,根据原始数组中的位置进行分组。
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 ());
}给定一系列有效的属性标识符和一个值数组,请返回将属性关联到值的对象。
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 );
}返回两个或多个数字的平均值。
public static double average ( int [] arr ) {
return IntStream . of ( arr )
. average ()
. orElseThrow (() -> new IllegalArgumentException ( "Array is empty" ));
}计算数字数组的最大共同点(GCD)。
使用Arrays.Stream()。redion()和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)。
使用Arrays.Stream()。redion()和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 );
}找到大于或等于值的下一个功率。
该方法使用左船舶操作员右侧的值将1移1。使用Integer.numberOfLeadingZeros方法计算右侧。
Integer.numberOfLeadingZeros给出了零的数量。例如,调用Integer.numberOfLeadingZeros(3)的值为30。这是因为3在二进制中表示为11 。由于整数具有32位,因此有30位,为0。左移动器的右侧变为32-30 = 2 。左移1乘2 IE 001 << 2是100 。十进制100等于4 。
public static int findNextPositivePowerOfTwo ( int value ) {
return 1 << ( 32 - Integer . numberOfLeadingZeros ( value - 1 ));
}检查数字是否甚至是。
此方法使用位和操作员。 0b1是1的二进制表示。由于Java 7,您可以通过将二进制文字写为0b或0B 。当数字均匀时,&运算符将返回0。例如, IsEven(4)将导致100 & 001 。 &将为000的结果。
public static boolean isEven ( final int value ) {
return ( value & 0b1) == 0 ;
}检查一个值是否为两个两个。
要了解它的工作原理,我们假设我们拨打了一个电话IsPowerOfTwo(4) 。
由于值大于0,因此将评估&&运算符的右侧。
(~value + 1)的结果等于值本身。 ~100 + 001 => 011 + 001 => 100 。这等于值。
(value & value)的结果是值。 100 & 100 => 100 。
这将重视表达式为true,因为值等于值。
public static boolean isPowerOfTwo ( final int value ) {
return value > 0 && (( value & (~ value + 1 )) == value );
}在Integer.MIN_VALUE和Integer.MAX_VALUE之间生成一个随机整数。
public static int generateRandomInt () {
return ThreadLocalRandom . current (). nextInt ();
}生成字符串的所有字符(包含重复)。
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 ());
}返回字节中的字符串长度。
public static int byteSize ( String input ) {
return input . getBytes (). length ;
}大写字符串的首字母。
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 ()));
}大写字符串中每个单词的首字母。
public static String capitalizeEveryWord ( final String input ) {
return Pattern . compile ( " \ b(?= \ w)" ). splitAsStream ( input )
. map ( w -> capitalize ( w , false ))
. collect ( Collectors . joining ());
}在提供的字符串中重新调整元音number 。
public static int countVowels ( String input ) {
return input . replaceAll ( "[^aeiouAEIOU]" , "" ). length ();
}逃脱一个字符串以在正则表达式中使用。
public static String escapeRegExp ( String input ) {
return Pattern . quote ( input );
}从骆驼转换一个字符串。
public static String fromCamelCase ( String input , String separator ) {
return input
. replaceAll ( "([a-z \ d])([A-Z])" , "$1" + separator + "$2" )
. toLowerCase ();
}如果给定的字符串是绝对的URL,则返回true ,否则为false 。
public static boolean isAbsoluteUrl ( String url ) {
return Pattern . compile ( "^[a-z][a-z0-9+.-]*:" ). matcher ( url ). find ();
}检查字符串是否较低。
public static boolean isLowerCase ( String input ) {
return Objects . equals ( input , input . toLowerCase ());
}检查字符串是否为上情况。
public static boolean isUpperCase ( String input ) {
return Objects . equals ( input , input . toUpperCase ());
}检查字符串是否为回文。
public static boolean isPalindrome ( String input ) {
String s = input . toLowerCase (). replaceAll ( "[ \ W_]" , "" );
return Objects . equals (
s ,
new StringBuilder ( s ). reverse (). toString ()
);
}检查字符串是否为数字。
public static boolean isNumeric ( final String input ) {
return IntStream . range ( 0 , input . length ())
. allMatch ( i -> Character . isDigit ( input . charAt ( i )));
}用指定的掩码字符替换了最后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 );
}逆转字符串。
public static String reverseString ( String input ) {
return new StringBuilder ( input ). reverse (). toString ();
}字母顺序分类字符串中的字符。
public static String sortCharactersInString ( String input ) {
return Arrays . stream ( input . split ( "" )). sorted (). collect ( Collectors . joining ());
}将多行字符串拆分为一条线数。
public static String [] splitLines ( String input ) {
return input . split ( " \ r? \ n" );
}将字符串转换为骆驼。
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 );
}将字符串转换为烤肉串。
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 ( "-" ));
} 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 ;
}将字符串转换为蛇案。
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 ( "_" ));
}将字符串截断为指定的长度。
public static String truncateString ( String input , int num ) {
return input . length () > num
? input . substring ( 0 , num > 3 ? num - 3 : num ) + "..."
: input ;
}将给定的字符串转换为单词数组。
public static String [] words ( String input ) {
return Arrays . stream ( input . split ( "[^a-zA-Z-]+" ))
. filter ( s -> ! s . isEmpty ())
. toArray ( String []:: new );
}将一串由空间分开的数字将其转换为INT数组。
public static int [] stringToIntegers ( String numbers ) {
return Arrays . stream ( numbers . split ( " " )). mapToInt ( Integer :: parseInt ). toArray ();
}将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 ());
}将文件的内容读取到字符串
public String readFileAsString ( Path path ) throws IOException {
return new String ( Files . readAllBytes ( path ));
} public static String getCurrentWorkingDirectoryPath () {
return FileSystems . getDefault (). getPath ( "" ). toAbsolutePath (). toString ();
}返回java.io.tmpdir系统属性的值。如果最后不存在,它会附加分离器。
public static String tmpDirName () {
String tmpDirName = System . getProperty ( "java.io.tmpdir" );
if (! tmpDirName . endsWith ( File . separator )) {
tmpDirName += File . separator ;
}
return tmpDirName ;
}将异常堆栈跟踪转换为字符串。
public static String stackTraceAsString ( final Throwable throwable ) {
final StringWriter sw = new StringWriter ();
throwable . printStackTrace ( new PrintWriter ( sw ));
return sw . toString ();
}将操作系统的名称作为较低的案例字符串。
public static String osName () {
return System . getProperty ( "os.name" ). toLowerCase ();
}检查是否将调试器附加到JVM上。
public static boolean isDebuggerAttached () {
final RuntimeMXBean runtimeMXBean = ManagementFactory . getRuntimeMXBean ();
return runtimeMXBean . getInputArguments ()
. stream ()
. anyMatch ( arg -> arg . contains ( "-agentlib:jdwp" ));
}此方法返回给定类及其超类实现的所有接口。
该方法通过连接两个流来起作用。第一个流是通过创建接口和接口实现的所有接口来递归构建的。第二个流对超级类的作用相同。结果是删除了重复项后两个流的串联。
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 ());
}此方法检查指定的类是内部类还是静态嵌套类
public static boolean isInnerClass ( final Class <?> cls ) {
return cls != null && cls . getEnclosingClass () != null ;
}转换为枚举以映射键是姓名和值是枚举本身。
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 ()));
}该项目最初是30秒的Java叉。感谢项目合作者的努力。