您可以快速理解的有用的小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叉。感謝項目合作者的努力。