คอลเลกชันคอลเลกชันของฟังก์ชั่น 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 (). ตัวกรอง (). นับ () นับจำนวนทั้งหมดของค่าที่เท่ากับค่าที่ระบุ
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 จากนั้นใช้ array.stream (). filter () บน A เพื่อเก็บค่าที่ไม่ได้อยู่ใน 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 ();
}กรองค่าทั้งหมดจากอาร์เรย์ที่ฟังก์ชั่นเปรียบเทียบไม่ส่งคืนจริง
ตัวเปรียบเทียบสำหรับ INT ถูกนำมาใช้โดยใช้ฟังก์ชัน intbinaryOperator
ใช้ array.stream (). ตัวกรองและอาร์เรย์ 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 (). แตกต่าง () เพื่อทิ้งค่าที่ซ้ำกันทั้งหมด
public static int [] distinctValuesOfArray ( int [] elements ) {
return Arrays . stream ( elements ). distinct (). toArray ();
}ลบองค์ประกอบในอาร์เรย์จนกว่าฟังก์ชั่นที่ผ่านจะส่งคืนจริง ส่งคืนองค์ประกอบที่เหลือในอาร์เรย์
วนลูปผ่านอาร์เรย์โดยใช้อาร์เรย์ copyofrange () เพื่อวางองค์ประกอบแรกของอาร์เรย์จนกว่าค่าที่ส่งคืนจากฟังก์ชันจะเป็นจริง ส่งคืนองค์ประกอบที่เหลือ
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 สั้นกว่าอาร์เรย์ที่กำหนดและใช้อาร์เรย์ 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 ];
}ส่งคืนทุกองค์ประกอบที่ n ในอาร์เรย์
ใช้ intstream.Range (). ตัวกรอง () เพื่อสร้างอาร์เรย์ใหม่ที่มีองค์ประกอบ 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 ();
}ค้นหาดัชนีขององค์ประกอบในอาร์เรย์ return -1 ในกรณีที่องค์ประกอบไม่มีอยู่
ใช้ intstream.Range (). ตัวกรอง () เพื่อค้นหาดัชนีขององค์ประกอบในอาร์เรย์
public static int indexOf ( int [] elements , int el ) {
return IntStream . range ( 0 , elements . length )
. filter ( idx -> elements [ idx ] == el )
. findFirst ()
. orElse (- 1 );
}ค้นหาดัชนีสุดท้ายขององค์ประกอบในอาร์เรย์ return -1 ในกรณีที่องค์ประกอบไม่มีอยู่
ใช้ intstream.iterate (). Limit (). ตัวกรอง () เพื่อค้นหาดัชนีขององค์ประกอบในอาร์เรย์
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 );
}กรองค่าที่ไม่ใช่ unique ในอาร์เรย์
ใช้ array.stream (). ตัวกรอง () สำหรับอาร์เรย์ที่มีค่าเฉพาะเท่านั้น
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 ();
}จัดกลุ่มองค์ประกอบของอาร์เรย์ตามฟังก์ชันที่กำหนด
ใช้ array.stream (). collect (collector.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 ();
}ส่งคืนรายการองค์ประกอบที่มีอยู่ในอาร์เรย์ทั้งสอง
สร้างชุดจากที่สองจากนั้นใช้ array.stream (). filter () บน A เพื่อเก็บค่าที่อยู่ใน 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 การสั่งซื้อสำหรับสององค์ประกอบแรกใช้งานวนซ้ำเพื่อทำซ้ำรายการอาร์เรย์และเปรียบเทียบเป็นคู่ ส่งคืน 0 หาก direction เปลี่ยนหรือ 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 ;
}เข้าร่วมองค์ประกอบทั้งหมดของอาร์เรย์ลงในสตริงและส่งคืนสตริงนี้ ใช้ตัวคั่นและตัวคั่นปลาย
ใช้ intstream.Range ไปยัง zip index ด้วยรายการอาร์เรย์ จากนั้นใช้ 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() เพื่อรับอาร์เรย์ที่มีองค์ประกอบ NTH ตั้งแต่แรก
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 )];
} รับองค์ประกอบสุ่ม n ที่คีย์ที่ไม่ซ้ำกันตั้งแต่ array จนถึงขนาดของ array
สลับอาร์เรย์โดยใช้อัลกอริทึม 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 ()));
}ส่งคืนองค์ประกอบทั้งหมดในอาร์เรย์ยกเว้นองค์ประกอบแรก
return 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 );
}ส่งคืนทุกองค์ประกอบที่มีอยู่ในสองอาร์เรย์หนึ่งครั้ง
สร้าง Set ที่มีค่าทั้งหมดของ a และ b และแปลงเป็นอาร์เรย์
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() เพื่อสร้างอาร์เรย์ยกเว้น (ใช้ !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 (). ลด () และสูตร 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 (). ลด () และสูตร 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 โดยค่าทางด้านขวา ด้านขวาคำนวณโดยใช้เมธอด Integer.numberOfLeadingZeros
Integer.numberOfLeadingZeros ให้จำนวนศูนย์นำมูลค่า ตัวอย่างเช่นการเรียก Integer.numberOfLeadingZeros(3) จะให้ค่าเป็น 30 นี่เป็นเพราะ 3 แสดงเป็นไบนารีเป็น 11 เนื่องจากจำนวนเต็มมี 32 บิตดังนั้นจึงมี 30 บิตกับ 0 ด้านขวาของตัวดำเนินการกะซ้ายจะกลายเป็น 32-30 = 2 การขยับ 1 โดย 2 คือ 001 << 2 จะเป็น 100 100 ในทศนิยมเท่ากับ 4
public static int findNextPositivePowerOfTwo ( int value ) {
return 1 << ( 32 - Integer . numberOfLeadingZeros ( value - 1 ));
}ตรวจสอบว่าหมายเลขนั้นมีอยู่หรือไม่
วิธีนี้ใช้ Bitwise & Operator 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
สิ่งนี้จะให้ความสำคัญกับการแสดงออกเป็นจริงเนื่องจากค่าเท่ากับค่า
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 ();
}สร้าง 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 ());
}ส่งคืนความยาวของสตริงเป็นไบต์
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 ());
} retuns number สระในสตริงที่ให้ไว้
public static int countVowels ( String input ) {
return input . replaceAll ( "[^aeiouAEIOU]" , "" ). length ();
}หลบหนีสตริงที่จะใช้ในนิพจน์ทั่วไป
public static String escapeRegExp ( String input ) {
return Pattern . quote ( input );
}แปลงสตริงจาก Camelcase
public static String fromCamelCase ( String input , String separator ) {
return input
. replaceAll ( "([a-z \ d])([A-Z])" , "$1" + separator + "$2" )
. toLowerCase ();
} ส่งคืน true ถ้าสตริงที่กำหนดเป็น URL สัมบูรณ์ 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 ());
}ตรวจสอบว่าสตริงเป็น palindrome หรือไม่
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 ());
}แยกสตริง multiline ออกเป็นอาร์เรย์ของเส้น
public static String [] splitLines ( String input ) {
return input . split ( " \ r? \ n" );
}แปลงสตริงเป็น Camelcase
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 ();
}แปลงอินพุตสตรีมเป็นสตริง
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" ));
}วิธีนี้จะส่งคืนอินเทอร์เฟซทั้งหมดที่ใช้โดยคลาสที่กำหนดและ superclasses
วิธีนี้ใช้งานได้โดยการเชื่อมต่อสองสตรีม สตรีมแรกถูกสร้างขึ้นซ้ำโดยการสร้างสตรีมด้วยอินเทอร์เฟซและอินเทอร์เฟซทั้งหมดที่ใช้โดยอินเทอร์เฟซ สตรีมที่สองทำเช่นเดียวกันสำหรับคลาส Super ผลที่ได้คือการต่อกันของลำธารทั้งสองหลังจากลบรายการซ้ำ
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 ;
}แปลงเป็น enum เป็นแผนที่ที่คีย์คือชื่อและค่าคือ enum ตัวเอง
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 ()));
}โครงการนี้เริ่มต้นเป็น Java Fork 30 วินาทีของรหัส ขอบคุณผู้ทำงานร่วมกันของโครงการสำหรับความพยายาม