Coleção com curadoria de funções úteis Java 8 que você pode entender rapidamente.
chunkcountOccurrencesdeepFlattendifferencedifferenceWithdistinctValuesOfArraydropElementsdropRighteveryNthfilterNonUniqueflattenflattenDepthgroupByheadinitialinitializeArrayWithRangeinitializeArrayWithValuesintersectionisSortedjoinnthElementpickreducedFilterremovesamplesampleSizeshufflesimilaritysortedIndexsymmetricDifferencetailtaketakeRightunionwithoutzipzipObjectaveragegcdlcmfindNextPositivePowerOfTwoisEvenisPowerOfTwogenerateRandomIntanagramsbyteSizecapitalizecapitalizeEveryWordcountVowelsescapeRegExpfromCamelCaseisAbsoluteURLisLowerCaseisUpperCaseisPalindromeisNumericmaskreverseStringsortCharactersInStringsplitLinestoCamelCasetoKebabCasematchtoSnakeCasetruncateStringwordsstringToIntegersconvertInputStreamToStringreadFileAsStringgetCurrentWorkingDirectoryPathtmpDirNamestackTraceAsStringosNameisDebuggerEnabledgetAllInterfacesIsInnerClassgetEnumMapPedaços de uma matriz em matrizes menores de tamanho especificado.
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 ()));
}Conta as ocorrências de um valor em uma matriz.
Use Arrays.Stream (). Filtro (). Contagem () para contar o número total de valores que são iguais ao valor especificado.
public static long countOccurrences ( int [] numbers , int value ) {
return Arrays . stream ( numbers )
. filter ( number -> number == value )
. count ();
}Deep achatar uma matriz.
Use recursão. Use 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 ();
}Retorna a diferença entre duas matrizes.
Crie um conjunto de B e use Arrays.Stream (). Filter () em A para manter apenas valores não contidos em 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 ();
}Filtra todos os valores de uma matriz para a qual a função do comparador não retorna true.
O comparador para int é implementado usando a função intbinaryOperator.
Usa Arrays.Stream (). Filter e Arrays.Stream (). NONEMATCH () para encontrar os valores apropriados.
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 ();
}Retorna todos os valores distintos de uma matriz.
Usa Arrays.Stream (). Distinct () para descartar todos os valores duplicados.
public static int [] distinctValuesOfArray ( int [] elements ) {
return Arrays . stream ( elements ). distinct (). toArray ();
}Remove os elementos em uma matriz até que a função passada retorne true. Retorna os elementos restantes na matriz.
Loop através da matriz, usando o Arrays.copyOfRange () para soltar o primeiro elemento da matriz até que o valor retornado da função seja verdadeiro. Retorna os elementos restantes.
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 ;
}Retorna uma nova matriz com n elementos removidos da direita.
Verifique se n é mais curto que a matriz dada e use a matriz.copyOfRange () para cortá -la de acordo ou retornar uma matriz vazia.
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 ];
}Retorna todos os enésimos elementos em uma matriz.
Use Intstream.Range (). Filter () para criar uma nova matriz que contém todos os enésimos elementos de uma determinada matriz.
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 ();
}Encontre o índice de elemento na matriz. Retornar -1 no caso do elemento não existir.
Usa o índice Intstream.Range (). Para encontrar o índice do elemento na matriz.
public static int indexOf ( int [] elements , int el ) {
return IntStream . range ( 0 , elements . length )
. filter ( idx -> elements [ idx ] == el )
. findFirst ()
. orElse (- 1 );
}Encontre o último índice de elemento na matriz. Retornar -1 no caso do elemento não existir.
Usa intstream.iterate (). Limite (). Filtro () para encontrar o índice do elemento na matriz.
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 );
}Filtra os valores que não são únicos em uma matriz.
Use Arrays.Stream (). Filtro () para uma matriz contendo apenas os valores exclusivos.
public static int [] filterNonUnique ( int [] elements ) {
return Arrays . stream ( elements )
. filter ( el -> indexOf ( elements , el ) == lastIndexOf ( elements , el ))
. toArray ();
}Achate uma matriz.
Use Arrays.Stream (). Flatmaptoint (). ToArray () para criar uma nova matriz.
public static int [] flatten ( Object [] elements ) {
return Arrays . stream ( elements )
. flatMapToInt ( el -> el instanceof int []
? Arrays . stream (( int []) el )
: IntStream . of (( int ) el )
). toArray ();
}Achate uma matriz até a profundidade especificada.
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 ();
}Agrupa os elementos de uma matriz com base na função fornecida.
Usa o Arrays.Stream (). Colete (colecionor.groupingby ()) para agrupar com base na função de agrupamento.
public static < T , R > Map < R , List < T >> groupBy ( T [] elements , Function < T , R > func ) {
return Arrays . stream ( elements ). collect ( Collectors . groupingBy ( func ));
}Retorna todos os elementos de uma matriz, exceto o último. Use Arrays.copyOfRange () para retornar tudo, exceto o último
public static < T > T [] initial ( T [] elements ) {
return Arrays . copyOfRange ( elements , 0 , elements . length - 1 );
}Inicializa uma matriz que contém os números no intervalo especificado, onde o início e o fim são inclusivos.
public static int [] initializeArrayWithRange ( int end , int start ) {
return IntStream . rangeClosed ( start , end ). toArray ();
}Inicializa e preenche uma matriz com os valores especificados.
public static int [] initializeArrayWithValues ( int n , int value ) {
return IntStream . generate (() -> value ). limit ( n ). toArray ();
}Retorna uma lista de elementos que existem em ambas as matrizes.
Crie um conjunto a partir do segundo e use Arrays.Stream (). Filtro () em A para manter apenas os valores contidos em 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 ();
} Retorna 1 Se a matriz for classificada em ordem ascendente, -1 se for classificada em ordem descendente ou 0 se não for classificada.
Calcule a direction de pedido para os dois primeiros elementos. Use o loop para iterar itens de matriz e compará -los em pares. Retorne 0 se a direction mudar ou a direction se o último elemento for alcançado.
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 ;
}Junta todos os elementos de uma matriz em uma string e retorna essa string. Usa um separador e um separador final.
Use o Intstream.Range para Zip Index com o item de matriz. Em seguida, use Stream.reduce para combinar elementos em uma string.
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 );
}Retorna o enésimo elemento de uma matriz.
Use Arrays.copyOfRange() para obter uma matriz contendo o enésimo elemento no primeiro lugar.
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 ];
}Escolha os pares de valor-chave correspondentes às teclas fornecidas de um objeto.
Use Arrays.stream para filtrar todas as teclas presentes no arr . Em seguida, converta todas as teclas presentes em um mapa usando 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 ));
}Filtre uma matriz de objetos com base em uma condição e também filtra as teclas não especificadas.
Use Arrays.stream().filter() para filtrar a matriz com base no Predicado fn para que ele retorne os objetos para os quais a condição é verdadeira. Para cada objeto de mapa filtrado, crie um novo mapa com chaves presentes nas keys . Finalmente, colete todo o objeto de mapa em uma matriz.
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 );
}Retorna um elemento aleatório de uma matriz.
Use Math.random() para gerar um número aleatório, multiplique -o por length e arredondá -lo para o número inteiro mais próximo usando Math.floor() . Este método também funciona com strings.
public static < T > T sample ( T [] arr ) {
return arr [( int ) Math . floor ( Math . random () * arr . length )];
} Obtém n elementos aleatórios em teclas exclusivas da array até o tamanho da array .
Embaralhar a matriz usando o algoritmo Fisher-Yates. Use Array.copyOfRange() para obter os primeiros n elementos.
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 );
}Randomiza a ordem dos valores de uma matriz, retornando uma nova matriz.
Usa o algoritmo Fisher-Yates para reordenar os elementos da matriz.
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 ;
}Retorna uma variedade de elementos que aparecem nas duas matrizes.
Use Arrays.stream().filter() para remover valores que não fazem parte do second , determinados usando 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 ()));
}Retorna o menor índice no qual o valor deve ser inserido na matriz para manter sua ordem de classificação.
Verifique se a matriz é classificada em ordem decrescente (vagamente). Use IntStream.range().filter() para encontrar o índice apropriado onde o elemento deve ser inserido.
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 );
}Retorna a diferença simétrica entre duas matrizes.
Crie um Set a partir de cada matriz e use Arrays.stream().filter() em cada um deles para manter apenas os valores não contidos no outro. Finalmente, concatenar as duas matrizes e criar uma nova matriz e devolvê -la.
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 ()));
}Retorna todos os elementos em uma matriz, exceto o primeiro.
Retornar Arrays.copyOfRange(1) Se o length da matriz for superior a 1 , caso contrário, retorne a matriz inteira.
public static < T > T [] tail ( T [] arr ) {
return arr . length > 1
? Arrays . copyOfRange ( arr , 1 , arr . length )
: arr ;
}Retorna uma matriz com n elementos removidos desde o início.
public static < T > T [] take ( T [] arr , int n ) {
return Arrays . copyOfRange ( arr , 0 , n );
}Retorna uma matriz com n elementos removidos do final.
Use Arrays.copyOfRange() para criar uma fatia da matriz com n elementos retirados do final.
public static < T > T [] takeRight ( T [] arr , int n ) {
return Arrays . copyOfRange ( arr , arr . length - n , arr . length );
}Retorna todos os elementos que existam em qualquer uma das duas matrizes uma vez.
Crie um Set com todos os valores de a e b e converta em uma matriz.
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 ()));
}Filtra os elementos de uma matriz, que possuem um dos valores especificados.
Use Arrays.strean().filter() para criar uma matriz excluindo (usando !Arrays.asList(elements).contains() ) todos os valores fornecidos.
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 ()));
}Cria uma variedade de elementos, agrupados com base na posição nas matrizes originais.
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 ());
}Dada uma variedade de identificadores de propriedade válidos e uma matriz de valores, retorne um objeto que associa as propriedades aos valores.
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 );
}Retorna a média de um de dois ou mais números.
public static double average ( int [] arr ) {
return IntStream . of ( arr )
. average ()
. orElseThrow (() -> new IllegalArgumentException ( "Array is empty" ));
}Calcula o maior denominador comum (GCD) de uma matriz de números.
Use Arrays.Stream (). Reduce () e a fórmula GCD (usa recursão) para calcular o maior denominador comum de uma matriz de números.
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 );
}Calcula o múltiplo comum mais baixo (LCM) de uma matriz de números.
Use Arrays.Stream (). Reduce () e a fórmula LCM (usa recursão) para calcular o múltiplo comum mais baixo de uma matriz de números.
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 );
}Encontra o próximo poder de dois maiores ou iguais ao valor.
Este método usa o operador de navio esquerdo para mudar 1 pelo valor no lado direito. O lado direito é calculado usando o método Integer.numberOfLeadingZeros .
O Integer.numberOfLeadingZeros fornece o número de zeros liderando o valor. Por exemplo, chamar Integer.numberOfLeadingZeros(3) daria valor a 30. Isso ocorre porque 3 é representado em binário como 11 . Como o número inteiro possui 32 bits, existem 30 bits com 0. O lado direito do operador de mudança esquerdo se torna 32-30 = 2 . A mudança de esquerda 1 por 2 isto é 001 << 2 seria 100 . 100 em decimal é igual a 4 .
public static int findNextPositivePowerOfTwo ( int value ) {
return 1 << ( 32 - Integer . numberOfLeadingZeros ( value - 1 ));
}Verifique se o número é par.
Este método usa Bitwise & Operator. O 0b1 é a representação binária de 1. Desde, Java 7, você pode escrever literais binários prefixando -os com 0b ou 0B . O Operador retornará 0 quando o número for uniforme. Por exemplo, IsEven(4) resultaria em 100 & 001 . O resultado de & será 000 .
public static boolean isEven ( final int value ) {
return ( value & 0b1) == 0 ;
}Verifica se um valor é poder positivo de dois.
Para entender como funciona, vamos supor que fizemos uma chamada IsPowerOfTwo(4) .
Como o valor é maior que 0, portanto, o lado direito do operador && será avaliado.
O resultado de (~value + 1) é igual ao valor em si. ~100 + 001 => 011 + 001 => 100 . Isso é igual ao valor.
O resultado de (value & value) é valor. 100 e 100 => 100 .
Isso valorizará a expressão para TRUE como valor é igual ao valor.
public static boolean isPowerOfTwo ( final int value ) {
return value > 0 && (( value & (~ value + 1 )) == value );
} Gere um número inteiro aleatório entre Integer.MIN_VALUE e Integer.MAX_VALUE .
public static int generateRandomInt () {
return ThreadLocalRandom . current (). nextInt ();
}Gera todos os anagramas de uma string (contém duplicatas).
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 ());
}Retorna o comprimento de uma corda em bytes.
public static int byteSize ( String input ) {
return input . getBytes (). length ;
}Capitaliza a primeira letra de uma corda.
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 ()));
}Capitaliza a primeira letra de cada palavra em uma string.
public static String capitalizeEveryWord ( final String input ) {
return Pattern . compile ( " \ b(?= \ w)" ). splitAsStream ( input )
. map ( w -> capitalize ( w , false ))
. collect ( Collectors . joining ());
} RETUNS number de vogais na string fornecida.
public static int countVowels ( String input ) {
return input . replaceAll ( "[^aeiouAEIOU]" , "" ). length ();
}Escapa de uma string para usar em uma expressão regular.
public static String escapeRegExp ( String input ) {
return Pattern . quote ( input );
}Converte uma corda de Camelcase.
public static String fromCamelCase ( String input , String separator ) {
return input
. replaceAll ( "([a-z \ d])([A-Z])" , "$1" + separator + "$2" )
. toLowerCase ();
} Retorna true se a string fornecida for um URL absoluto, false caso contrário.
public static boolean isAbsoluteUrl ( String url ) {
return Pattern . compile ( "^[a-z][a-z0-9+.-]*:" ). matcher ( url ). find ();
}Verifica se uma string é minúscula.
public static boolean isLowerCase ( String input ) {
return Objects . equals ( input , input . toLowerCase ());
}Verifica se uma string é mais alta.
public static boolean isUpperCase ( String input ) {
return Objects . equals ( input , input . toUpperCase ());
}Verifica se uma string é palíndrome.
public static boolean isPalindrome ( String input ) {
String s = input . toLowerCase (). replaceAll ( "[ \ W_]" , "" );
return Objects . equals (
s ,
new StringBuilder ( s ). reverse (). toString ()
);
}Verifica se uma string é numérica.
public static boolean isNumeric ( final String input ) {
return IntStream . range ( 0 , input . length ())
. allMatch ( i -> Character . isDigit ( input . charAt ( i )));
} Substitui todos, exceto o último num de caracteres pelo caractere de máscara especificado.
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 );
}Reverte uma string.
public static String reverseString ( String input ) {
return new StringBuilder ( input ). reverse (). toString ();
}Alfabeticamente classifica os caracteres em uma string.
public static String sortCharactersInString ( String input ) {
return Arrays . stream ( input . split ( "" )). sorted (). collect ( Collectors . joining ());
}Divide uma corda multilina em uma variedade de linhas.
public static String [] splitLines ( String input ) {
return input . split ( " \ r? \ n" );
}Converte uma corda em 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 );
}Converte uma string em estojo de kebab.
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 ;
}Converte um caso de string em cobra.
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 ( "_" ));
}Trunca uma string até um comprimento especificado.
public static String truncateString ( String input , int num ) {
return input . length () > num
? input . substring ( 0 , num > 3 ? num - 3 : num ) + "..."
: input ;
}Converte uma determinada string em uma matriz de palavras.
public static String [] words ( String input ) {
return Arrays . stream ( input . split ( "[^a-zA-Z-]+" ))
. filter ( s -> ! s . isEmpty ())
. toArray ( String []:: new );
}Converte uma sequência de números separados pelo espaço em uma matriz de INTs.
public static int [] stringToIntegers ( String numbers ) {
return Arrays . stream ( numbers . split ( " " )). mapToInt ( Integer :: parseInt ). toArray ();
}Converte o InputStream em uma 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 ());
}Lê o conteúdo de um arquivo em uma string
public String readFileAsString ( Path path ) throws IOException {
return new String ( Files . readAllBytes ( path ));
} public static String getCurrentWorkingDirectoryPath () {
return FileSystems . getDefault (). getPath ( "" ). toAbsolutePath (). toString ();
} Retorna o valor da propriedade do sistema java.io.tmpdir . Ele anexa o separador se não estiver presente no final.
public static String tmpDirName () {
String tmpDirName = System . getProperty ( "java.io.tmpdir" );
if (! tmpDirName . endsWith ( File . separator )) {
tmpDirName += File . separator ;
}
return tmpDirName ;
}Converte o rastreamento da pilha de exceção em uma string.
public static String stackTraceAsString ( final Throwable throwable ) {
final StringWriter sw = new StringWriter ();
throwable . printStackTrace ( new PrintWriter ( sw ));
return sw . toString ();
}Obtém o nome do sistema operacional como uma string minúscula.
public static String osName () {
return System . getProperty ( "os.name" ). toLowerCase ();
}Verifica se o depurador está anexado à JVM.
public static boolean isDebuggerAttached () {
final RuntimeMXBean runtimeMXBean = ManagementFactory . getRuntimeMXBean ();
return runtimeMXBean . getInputArguments ()
. stream ()
. anyMatch ( arg -> arg . contains ( "-agentlib:jdwp" ));
}Isso métodos retorna todas as interfaces implementadas pela classe fornecida e suas superclasses.
Este método funciona concatenando dois fluxos. O primeiro fluxo é construído recursivamente, criando um fluxo com a interface e todas as interfaces implementadas pela interface. O segundo fluxo faz o mesmo para as super classes. O resultado é a concatenação dos dois fluxos após a remoção das duplicatas.
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 ());
}Este método verifica se a classe especificada é uma classe interna ou classe aninhada estática
public static boolean isInnerClass ( final Class <?> cls ) {
return cls != null && cls . getEnclosingClass () != null ;
}Converter para enum para mapear onde a chave é o nome e o valor é a própria enumeração.
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 ()));
}Este projeto começou como um garfo Java de 30 segundos de código. Obrigado aos colaboradores do projeto pelo esforço.