Collection of reusable tested Java 21 compatible code snippets that you can understand in 30 seconds or less.
Collection of reusable tested Java 21 compatible code snippets that you can understand in 30 seconds or less.
Inspired by 30 seconds of code, this is a collection of reusable, tested, and copy-pasteable Java 21 compatible code snippets that you can understand in 30 seconds or less. If you're interested in contributing to this library, please see the contribution guidelines.
…public class BubbleSortSnippet {
/**
* Sort an array with bubbleSort algorithm.
*
* @param arr array to sort
*/
public static void bubbleSort(int[] arr) {
var lastIndex = arr.length - 1;
for (var j = 0; j arr[i + 1]) {
var tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
}
}
}
}
}public class CountingSortSnippet {
/**
* Sort an array having zero or positive numbers with countingSort algorithm.
*
* @param arr array to sort
*/
public static void countingSort(int[] arr) {
var max = Arrays.stream(arr).max().getAsInt();
var count = new int[max + 1];
for (var num : arr) {
count[num]++;
}
for (var i = 1; i = 0; i--) {
var cur = arr[i];
sorted[count[cur] - 1] = cur;
count[cur]--;
}
var index = 0;
for (var num : sorted) {
arr[index++] = num;
}
}
}public class CycleSortSnippet {
/**
* Sort an array with cycleSort algorithm.
*
* @param arr array to sort
*/
public static int[] cycleSort(int[] arr) {
int n = arr.length;
int i = 0;
while (i = 0 && arr[j] > tmp) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = tmp;
}
}
}……public class SelectionSortSnippet {
/**
* Sort an array with selectionSort algorithm.
*
* @param arr array to sort
*/
public static void selectionSort(int[] arr) {
var len = arr.length;
for (var i = 0; i the element type
* @return true if all elements in the array are equal
*/
public static boolean allEqual(T[] arr) {
return Arrays.stream(arr).distinct().count() == 1;
}
}public class ArrayConcatSnippet {
/**
* Generic 2 array concatenation Credits: Joachim Sauer https://stackoverflow.com/questions/80476/how-can-i-concatenate-two-arrays-in-java
*
* @param first is the first array (not null)
* @param second is the second array (not null)
* @param the element type
* @return concatenated array
*/
public static T[] arrayConcat(T[] first, T[] second) {
var result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
}public class ArrayMeanSnippet {
/**
* Returns the mean of the integers in the array.
*
* @param arr the array of integers (not null)
* @return a double representing the mean of the array
*/
public static double arrayMean(int[] arr) {
return (double) Arrays.stream(arr).sum() / arr.length;
}
}public class ArrayMedianSnippet {
/**
* Returns the median of the array.
*
* @param arr the array of integers (not null)
* @return a double representing the median of the array
*/
public static double arrayMedian(int[] arr) {
Arrays.sort(arr);
var mid = arr.length / 2;
return arr.length % 2 != 0 ? (double) arr[mid] : (double) (arr[mid] + arr[mid - 1]) / 2;
}
}public class ArrayModeInPlaceSnippet {
/**
* Returns the mode of the array.
*
* @param arr array to find mode in it
* @return mode of array
*/
public static int modeArrayInPlace(int[] arr) {
if (arr.length == 0) {
return 0;
}
Arrays.sort(arr);
int mode = arr[0];
int maxcount = 1;
int count = 1;
for (int i = 1; i maxcount) {
maxcount = count;
mode = arr[i - 1];
}
count = 1;
}
}
if (count > maxcount) {
mode = arr[arr.length - 1];
}
return mode;
}
}…public class ArraySumSnippet {
/**
* Returns sum of the integers in the array.
*
* @param arr the array of integers (not null)
* @return the sum of the elements from the array
*/
public static int arraySum(int[] arr) {
return Arrays.stream(arr).sum();
}
}public class FindMaxSnippet {
/**
* Returns the maximum integer from the array using reduction.
*
* @param arr the array of integers (not null)
* @return the maximum element from the array
*/
public static int findMax(int[] arr) {
return Arrays.stream(arr).reduce(Integer.MIN_VALUE, Integer::max);
}
}public class FindMinSnippet {
/**
* Returns the minimum integer from the array using reduction.
*
* @param arr the array of integers (not null)
* @return the minimum element from the array
*/
public static int findMin(int[] arr) {
return Arrays.stream(arr).reduce(Integer.MAX_VALUE, Integer::min);
}
}……public class GetAllMethodsSnippet {
/**
* Print all declared methods of the class.
*
* @param cls Tested class
* @return list of methods name
*/
public static List getAllMethods(final Class cls) {
return Arrays.stream(cls.getDeclaredMethods())
.map(Method::getName)
.collect(Collectors.toList());
}
}public class SafeCastSnippet {
/**
* Safely casts an object to the specified type.
*
* @param obj object to cast
* @param clazz target type
* @param target type parameter
* @return optional containing the cast object, or empty if the object is not
* assignable to the target type
*/
public static Optional safeCast(final Object obj, final Class clazz) {
return clazz.isInstance(obj) ? Optional.of(clazz.cast(obj)) : Optional.empty();
}
}public class GetAllPublicFieldNamesSnippet {
/**
* Print all declared public field names of the class or the interface the class extends.
*
* @param clazz Tested class
* @return list of name of public fields
*/
public static List getAllPublicFieldNames(final Class clazz) {
return Arrays.stream(clazz.getFields())
.map(Field::getName)
.collect(Collectors.toList());
}
}……public class Base64DecodeSnippet {
/**
* Decodes a Base64 encoded string to the actual representation.
*
* @param input base64 encoded string
* @return decoded string
*/
public static String decodeBase64(String input) {
return new String(Base64.getDecoder().decode(input.getBytes()));
}
}public class Base64EncodeSnippet {
/**
* Encodes the input string to a Base64 encoded string.
*
* @param input string to be encoded
* @return base64 encoded string
*/
public static String encodeBase64(String input) {
return Base64.getEncoder().encodeToString(input.getBytes());
}
}…public class ListDirectoriesSnippet {
/**
* List directories.
*
* @param path the path where to look
* @return array of File
*/
public static File[] listDirectories(String path) {
return new File(path).listFiles(File::isDirectory);
}
}public class ListFilesInDirectorySnippet {
/**
* List files in directory.
*
* @param folder the path where to look
* @return array of File
*/
public static File[] listFilesInDirectory(String folder) {
return new File(folder).listFiles(File::isFile);
}
}public class ReadLinesSnippet {
/**
* Read file as list of strings.
*
* @param filename the filename to read from
* @return list of strings
* @throws IOException if an I/O error occurs
*/
public static List readLines(String filename) throws IOException {
return Files.readAllLines(Paths.get(filename));
}
}………public class InputStreamToStringSnippet {
/**
* Convert InputStream to String.
*
* @param inputStream InputStream to convert
* @return String
*/
public static String inputStreamToString(InputStream inputStream) {
return new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
.lines().collect(Collectors.joining(System.lineSeparator()));
}
}public class ReadFileSnippet {
/**
* Read file using stream and return list of string lines.
*
* @param fileName file to read
* @throws FileNotFoundException if an I/O error occurs
*/
public static List readFile(String fileName) throws FileNotFoundException {
try (Stream stream = new BufferedReader(new FileReader(fileName)).lines()) {
return stream.collect(Collectors.toList());
}
}
}public class GetEnvOrDefaultSnippet {
/**
* Read an environment variable or return a default value when it is missing.
*
* @param key environment variable name
* @param defaultValue value returned when the variable is missing
* @return environment variable value or default value
*/
public static String getEnvOrDefault(String key, String defaultValue) {
return System.getenv().getOrDefault(key, defaultValue);
}
}……………public class CompareVersionSnippet {
private static final String EXTRACT_VERSION_REGEX = ".*?((? uniqueCharacters = new HashSet<>();
for (char character : charsOfStr) {
uniqueCharacters.add(String.valueOf(character));
}
return String.join("", uniqueCharacters);
}
}……public class ThreadSnippet {
/**
* Creates and returns a new thread with the task assigned to it (task will be performed parallel to the main thread).
*
* @param task the task to be executed by this thread
* @return new thread with task assigned to it.
*/
public static Thread createThread(Runnable task) {
return new Thread(task);
}
}public class ThreadPool {
/**
*
Creates pool of threads. Where the pool is the size of the number of processors
* available to the Java virtual machine.
*
* @return the newly created thread pool
*/
public static ExecutorService createFixedThreadPool() {
return Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
}
}…No open issues yet, or sync has not completed.