| title | Essential Code Snippets Library for Java Developers |
|---|---|
| shortTitle | Code Snippets Library |
| description | Access a wide range of Java code snippets for implementing design patterns effectively. Our library offers ready-to-use examples to help you improve your coding and design skills. |
| language | en |
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.
publicclassBinarySearchIn2dArraySnippet {
/** * Search an item with binarySearch algorithm. * * @param matrix should be sorted * @param target an item to search * @return if location of item is found, otherwise return {-1,-1} */publicstaticint[] binarySearchIn2darr(int[][] matrix, inttarget) {
introws = matrix.length - 1;
intcols = matrix[0].length - 1;
if (rows == 1) {
returnbinarySearch(matrix, target, 0, 0, cols);
}
intrstart = 0;
intrend = rows;
intcmid = cols / 2;
while (rstart < rend - 1) {
intrmid = rstart + (rend - rstart) / 2;
if (matrix[rmid][cmid] > target) {
rend = rmid;
} elseif (matrix[rmid][cmid] < target) {
rstart = rmid;
} else {
returnnewint[]{rmid, cmid};
}
}
if (matrix[rstart][cmid] == target) {
returnnewint[]{rstart, cmid};
}
if (matrix[rend][cmid] == target) {
returnnewint[]{rend, cmid};
}
if (target <= matrix[rstart][cmid - 1]) {
returnbinarySearch(matrix, target, rstart, 0, cmid - 1);
}
if (target >= matrix[rstart][cmid + 1]) {
returnbinarySearch(matrix, target, rstart, cmid + 1, cols);
}
if (target <= matrix[rend][cmid - 1]) {
returnbinarySearch(matrix, target, rend, 0, cmid - 1);
}
if (target <= matrix[rend][cmid + 1]) {
returnbinarySearch(matrix, target, rend, cmid + 1, cols);
}
returnnewint[]{-1, -1};
}
staticint[] binarySearch(int[][] matrix, inttarget, introw, intcstart, intcend) {
while (cstart <= cend) {
intcmid = cstart + (cend - cstart) / 2;
if (matrix[row][cmid] > target) {
cend = cmid - 1;
} elseif (matrix[row][cmid] < target) {
cstart = cend + 1;
} else {
returnnewint[]{row, cmid};
}
}
returnnewint[]{-1, -1};
}
}publicclassBinarySearchSnippet {
/** * Search an item with binarySearch algorithm. * * @param arr sorted array to search * @param item an item to search * @return if item is found, return the index position of the array item, otherwise return -1 */publicstaticintbinarySearch(int[] arr, intleft, intright, intitem) {
if (right >= left) {
intmid = left + (right - left) / 2;
if (arr[mid] == item) {
returnmid;
}
if (arr[mid] > item) {
returnbinarySearch(arr, left, mid - 1, item);
}
returnbinarySearch(arr, mid + 1, right, item);
}
return -1;
}
}publicclassBubbleSortSnippet {
/** * Sort an array with bubbleSort algorithm. * * @param arr array to sort */publicstaticvoidbubbleSort(int[] arr) {
varlastIndex = arr.length - 1;
for (varj = 0; j < lastIndex; j++) {
for (vari = 0; i < lastIndex - j; i++) {
if (arr[i] > arr[i + 1]) {
vartmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
}
}
}
}
}publicclassCountingSortSnippet {
/** * Sort an array having zero or positive numbers with countingSort algorithm. * * @param arr array to sort */publicstaticvoidcountingSort(int[] arr) {
varmax = Arrays.stream(arr).max().getAsInt();
varcount = newint[max + 1];
for (varnum : arr) {
count[num]++;
}
for (vari = 1; i <= max; i++) {
count[i] += count[i - 1];
}
varsorted = newint[arr.length];
for (vari = arr.length - 1; i >= 0; i--) {
varcur = arr[i];
sorted[count[cur] - 1] = cur;
count[cur]--;
}
varindex = 0;
for (varnum : sorted) {
arr[index++] = num;
}
}
}publicclassCycleSortSnippet {
/** * Sort an array with cycleSort algorithm. * * @param arr array to sort */publicstaticint[] cycleSort(int[] arr) {
intn = arr.length;
inti = 0;
while (i < n) {
intcorrectpos = arr[i] - 1;
if (arr[i] != arr[correctpos]) {
inttemp = arr[i];
arr[i] = arr[correctpos];
arr[correctpos] = temp;
} else {
i++;
}
}
returnarr;
}
}publicclassInsertionSortSnippet {
/** * Sort an array with insertionSort algorithm. * * @param arr array to sort */publicstaticvoidinsertionSort(int[] arr) {
for (vari = 1; i < arr.length; i++) {
vartmp = arr[i];
varj = i - 1;
while (j >= 0 && arr[j] > tmp) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = tmp;
}
}
}publicclassLinearSearchIn2dArraySnippet {
/** * Search an item with linearSearch algorithm. * * @param arr array to search * @param target an item to search * @return if location of target is found,otherwise return {-1,-1} */publicstaticint[] linearSearch2dArray(int[][] arr, inttarget) {
for (inti = 0; i < arr.length; i++) {
for (intj = 0; j < arr[i].length; j++) {
if (arr[i][j] == target) {
returnnewint[]{i, j};
}
}
}
returnnewint[]{-1, -1};
}
}publicclassLinearSearchSnippet {
/** * Search an item with linearSearch algorithm. * * @param arr array to search * @param item an item to search * @return if item is found, return the index position of the array item otherwise return -1 */publicstaticintlinearSearch(int[] arr, intitem) {
for (inti = 0; i < arr.length; i++) {
if (item == arr[i]) {
returni;
}
}
return -1;
}
}publicclassLuhnModnSnippet {
privatestaticfinalStringCODE_POINTS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/** * Generates a check character using the Luhn mod N algorithm. * * @param character the input string consisting of valid alphanumeric characters * @return the generated check character * @throws IllegalArgumentException if the input contains invalid characters */publicstaticintcodePointFromCharacter(charcharacter) {
if (CODE_POINTS.indexOf(character) == -1) {
thrownewIllegalArgumentException("Invalid character: " + character);
}
returnCODE_POINTS.indexOf(character);
}
/** * Converts a code point to its corresponding character. * * @param codePoint the code point to be converted * @return the character representation of the code point * @throws IllegalArgumentException if the code point is out of range. */publicstaticcharcharacterFromCodePoint(intcodePoint) {
if (codePoint < 0 || codePoint >= CODE_POINTS.length()) {
thrownewIllegalArgumentException("Invalid code point: " + codePoint);
}
returnCODE_POINTS.charAt(codePoint);
}
publicstaticintnumberOfValidInputCharacters() {
returnCODE_POINTS.length();
}
/** * Helper method to calculate the sum for both check character generation and validation. * * @param input the input string * @param factorStart the initial factor to start with (1 or 2) * @return the calculated sum, reminder, and the numberOfValidInputCharacters */privatestaticint[] calculateSum(Stringinput, intfactorStart) {
if (input == null || input.isEmpty()) {
thrownewIllegalArgumentException("Input cannot be empty");
}
intfactor = factorStart;
intsum = 0;
intn = numberOfValidInputCharacters();
for (inti = input.length() - 1; i >= 0; i--) {
intcodePoint = codePointFromCharacter(input.charAt(i));
intaddend = factor * codePoint;
factor = (factor == 2) ? 1 : 2;
addend = (addend / n) + (addend % n);
sum += addend;
}
returnnewint[]{sum, sum % n, n};
}
/** * Generates a check character for the given input string using the Luhn mod N algorithm. * * @param input the input string (non-empty) * @return the generated check character * @throws IllegalArgumentException if the input is null or empty */publicstaticchargenerateCheckCharacter(Stringinput) {
int[] result = calculateSum(input, 2);
returncharacterFromCodePoint((result[2] - result[1]) % result[2]);
}
/** * Validates a check character by applying the Luhn mod N algorithm. * * @param input the input string (including the check character) * @return true if the input passes validation, false otherwise * @throws IllegalArgumentException if the input is null or empty */publicstaticbooleanvalidateCheckCharacter(Stringinput) {
int[] result = calculateSum(input, 1);
return (result[1] == 0);
}
}publicclassMergeSortSnippet {
/** * Sort an array with qmergesort algorithm. * * @param arr array to sort * @low low index where to begin sort (e.g. 0) * @high high index where to end sort (e.g. array length - 1) */publicstaticvoidmergeSort(int[] arr, intlow, inthigh) {
if (low >= high) {
return;
}
varmid = (low + high) / 2;
mergeSort(arr, low, mid);
mergeSort(arr, mid + 1, high);
merge(arr, low, high, mid);
}
privatestaticvoidmerge(int[] arr, intlow, inthigh, intmid) {
int[] temp = newint[(high - low + 1)];
vari = low;
varj = mid + 1;
vark = 0;
while (i <= mid && j <= high) {
if (arr[i] < arr[j]) {
temp[k++] = arr[i];
i++;
} else {
temp[k++] = arr[j];
j++;
}
}
while (i <= mid) {
temp[k++] = arr[i];
i++;
}
while (j <= high) {
temp[k++] = arr[j];
j++;
}
for (intm = 0, n = low; m < temp.length; m++, n++) {
arr[n] = temp[m];
}
}
}publicclassQuickSortSnippet {
/** * Sort an array with quicksort algorithm. * * @param arr array to sort * @param left left index where to begin sort (e.g. 0) * @param right right index where to end sort (e.g. array length - 1) */publicstaticvoidquickSort(int[] arr, intleft, intright) {
varpivotIndex = left + (right - left) / 2;
varpivotValue = arr[pivotIndex];
vari = left;
varj = right;
while (i <= j) {
while (arr[i] < pivotValue) {
i++;
}
while (arr[j] > pivotValue) {
j--;
}
if (i <= j) {
vartmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
if (left < i) {
quickSort(arr, left, j);
}
if (right > i) {
quickSort(arr, i, right);
}
}
}
}publicclassSelectionSortSnippet {
/** * Sort an array with selectionSort algorithm. * * @param arr array to sort */publicstaticvoidselectionSort(int[] arr) {
varlen = arr.length;
for (vari = 0; i < len - 1; i++) {
varminIndex = i;
for (varj = i + 1; j < len; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
vartmp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = tmp;
}
}
}publicclassSieveOfEratosthenesSnippet {
/** * Search an item with binarySearch algorithm. * * @param n range of number. * @return isPrime boolean array where prime number 0 to n are mark true. */publicstaticboolean[] sieveOfEratosthenes(intn) {
boolean[] isPrime = newboolean[n + 1];
for (inti = 0; i < isPrime.length; i++) {
isPrime[i] = true;
}
for (inti = 2; i * i <= n; i++) {
if (isPrime[i] == true) {
for (intj = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
returnisPrime;
}
}publicclassVerhoeffSnippet {
privatestaticfinalint[][] d = {
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
{1, 0, 3, 2, 5, 4, 7, 6, 9, 8},
{2, 3, 0, 1, 6, 7, 4, 5, 8, 9},
{3, 2, 1, 0, 7, 6, 5, 4, 9, 8},
{4, 5, 6, 7, 0, 1, 2, 3, 8, 9},
{5, 4, 7, 6, 1, 0, 3, 2, 9, 8},
{6, 7, 4, 5, 2, 3, 0, 1, 8, 9},
{7, 6, 5, 4, 3, 2, 1, 0, 9, 8},
{8, 9, 8, 9, 8, 9, 8, 9, 0, 1},
{9, 8, 9, 8, 9, 8, 9, 8, 1, 0}
};
privatestaticfinalint[][] p = {
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
{1, 5, 7, 6, 2, 8, 3, 0, 9, 4},
{5, 8, 0, 3, 7, 9, 6, 1, 4, 2},
{8, 9, 1, 6, 0, 4, 3, 5, 2, 7},
{9, 4, 5, 3, 1, 2, 6, 8, 7, 0},
{4, 2, 8, 6, 5, 7, 3, 9, 0, 1},
{2, 7, 9, 3, 8, 0, 6, 4, 1, 5},
{7, 0, 4, 6, 9, 1, 3, 2, 5, 8}
};
privatestaticfinalint[] inv = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9};
/** * Validates a number using the Verhoeff checksum algorithm. * * @param num the numeric string to validate * @return true if the number is valid according to Verhoeff algorithm, false otherwise */publicstaticbooleanvalidateVerhoeff(Stringnum) {
intc = 0;
intlength = num.length();
// Adjust index for validation of the full number (including check digit)for (inti = 0; i < length; i++) {
intdigit = Character.getNumericValue(num.charAt(length - i - 1));
c = d[c][p[(i + 1) % 8][digit]]; // Correct permutation index
}
returnc == 0; // Final checksum must be zero
}
/** * Generates a Verhoeff check digit for a given numeric string. * * @param num the numeric string for which to generate the check digit * @return the generated Verhoeff check digit as a string */publicstaticStringgenerateVerhoeff(Stringnum) {
intc = 0;
intlength = num.length();
for (inti = 0; i < length; i++) {
intdigit = Character.getNumericValue(num.charAt(length - i - 1));
c = d[c][p[(i % 8)][digit]];
}
returnInteger.toString(inv[c]);
}
}publicclassAllEqualSnippet {
/** * Returns true if all elements in array are equal. * * @param arr the array to check (not null) * @param <T> the element type * @return true if all elements in the array are equal */publicstatic <T> booleanallEqual(T[] arr) {
returnArrays.stream(arr).distinct().count() == 1;
}
}publicclassArrayConcatSnippet {
/** * 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 <T> the element type * @return concatenated array */publicstatic <T> T[] arrayConcat(T[] first, T[] second) {
varresult = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
returnresult;
}
}publicclassArrayMeanSnippet {
/** * 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 */publicstaticdoublearrayMean(int[] arr) {
return (double) Arrays.stream(arr).sum() / arr.length;
}
}publicclassArrayMedianSnippet {
/** * Returns the median of the array. * * @param arr the array of integers (not null) * @return a double representing the median of the array */publicstaticdoublearrayMedian(int[] arr) {
Arrays.sort(arr);
varmid = arr.length / 2;
returnarr.length % 2 != 0 ? (double) arr[mid] : (double) (arr[mid] + arr[mid - 1]) / 2;
}
}publicclassArrayModeInPlaceSnippet {
/** * Returns the mode of the array. * * @param arr array to find mode in it * @return mode of array */publicstaticintmodeArrayInPlace(int[] arr) {
if (arr.length == 0) {
return0;
}
Arrays.sort(arr);
intmode = arr[0];
intmaxcount = 1;
intcount = 1;
for (inti = 1; i < arr.length; i++) {
if (arr[i] == arr[i - 1]) {
count++;
} else {
if (count > maxcount) {
maxcount = count;
mode = arr[i - 1];
}
count = 1;
}
}
if (count > maxcount) {
mode = arr[arr.length - 1];
}
returnmode;
}
}publicclassArrayModeSnippet {
/** * Private constructor to prevent instantiation. */privateArrayModeSnippet() {
thrownewIllegalStateException("Utility class");
}
/** * Returns the mode(s) of the array. * If multiple modes exist, it returns them in a list. */publicstaticList<Integer> modeArray(int[] arr) {
intmaxCount = 0;
HashMap<Integer, Integer> frequencyMap = newHashMap<>();
for (intnum : arr) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
maxCount = Math.max(maxCount, frequencyMap.get(num));
}
List<Integer> modes = newArrayList<>();
for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
if (entry.getValue() == maxCount) {
modes.add(entry.getKey());
}
}
returnmodes;
}
}publicclassArraySumSnippet {
/** * 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 */publicstaticintarraySum(int[] arr) {
returnArrays.stream(arr).sum();
}
}publicclassFindMaxSnippet {
/** * Returns the maximum integer from the array using reduction. * * @param arr the array of integers (not null) * @return the maximum element from the array */publicstaticintfindMax(int[] arr) {
returnArrays.stream(arr).reduce(Integer.MIN_VALUE, Integer::max);
}
}publicclassFindMinSnippet {
/** * Returns the minimum integer from the array using reduction. * * @param arr the array of integers (not null) * @return the minimum element from the array */publicstaticintfindMin(int[] arr) {
returnArrays.stream(arr).reduce(Integer.MAX_VALUE, Integer::min);
}
}publicclassMultiArrayConcatenationSnippet {
/** * Generic N 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 rest the rest of the arrays (optional) * @param <T> the element type * @return concatenated array */publicstatic <T> T[] multiArrayConcat(T[] first, T[]... rest) {
vartotalLength = first.length;
for (vararray : rest) {
totalLength += array.length;
}
varresult = Arrays.copyOf(first, totalLength);
varoffset = first.length;
for (vararray : rest) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
returnresult;
}
}publicclassReverseArraySnippet {
/** * The function then reverses the elements of the array between the starting and ending * indices using a while loop and a temporary variable `temp`. Finally, the function returns * the reversed array. * * @param array a array * @param start start index array * @param end end index array * @return reverses elements in the array * @throws IllegalArgumentException if the [start] index is greater * than the [end] index or if the array is null **/publicstatic <T> T[] reverseArray(T[] array, intstart, intend) {
if (start > end || array == null) {
thrownewIllegalArgumentException("Invalid argument!");
}
intminimumSizeArrayForReversal = 2;
if (start == end || array.length < minimumSizeArrayForReversal) {
returnarray;
}
while (start < end) {
Ttemp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
returnarray;
}
}publicclassCreatingObjectSnippet {
/** * Create object using reflection. * * @param cls fully qualified name of class includes the package name as String * @return object * @throws NoSuchMethodException if a method that does not exist at runtime. * @throws IllegalAccessException <p>if an currently executing method does not have access to * the definition of the specified class, field, method or constructor</p> * @throws InvocationTargetException <p>InvocationTargetException is a checked exception * that wraps an exception thrown by an invoked method or constructor.</p> * @throws InstantiationException <p>when an method tries to create an instance of a class * using the newInstance method in class Class.</p> * @throws ClassNotFoundException <p>when an application tries to load in a class * through its string name.</p> */publicstaticObjectcreateObject(Stringcls)
throwsNoSuchMethodException,
IllegalAccessException,
InvocationTargetException,
InstantiationException,
ClassNotFoundException {
varobjectClass = Class.forName(cls);
varobjectConstructor = objectClass.getConstructor();
returnobjectConstructor.newInstance();
}
}publicclassGetAllFieldNamesSnippet {
/** * Print all declared field names of the class or the interface the class extends. * * @param clazz Tested class * @return list of names of all fields */publicstaticList<String> getAllFieldNames(finalClass<?> clazz) {
varfields = newArrayList<String>();
varcurrentClazz = clazz;
while (currentClazz != null) {
fields.addAll(
Arrays.stream(currentClazz.getDeclaredFields())
.filter(field -> !field.isSynthetic())
.map(Field::getName)
.collect(Collectors.toList()));
currentClazz = currentClazz.getSuperclass();
}
returnfields;
}
}publicclassGetAllMethodsSnippet {
/** * Print all declared methods of the class. * * @param cls Tested class * @return list of methods name */publicstaticList<String> getAllMethods(finalClass<?> cls) {
returnArrays.stream(cls.getDeclaredMethods())
.map(Method::getName)
.collect(Collectors.toList());
}
}publicclassGetAllPublicFieldNamesSnippet {
/** * 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 */publicstaticList<String> getAllPublicFieldNames(finalClass<?> clazz) {
returnArrays.stream(clazz.getFields())
.map(Field::getName)
.collect(Collectors.toList());
}
}publicclassAddDaysToDateSnippet {
/** * Add days to given date. * * @param date given date * @param noOfDays number of days to add * @return modified date */publicstaticDateaddDaysToDate(Datedate, intnoOfDays) {
if (date != null) {
Calendarcal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, noOfDays);
returncal.getTime();
}
returnnull;
}
/** * Add days to local date. * * @param date given local date * @param noOfDays number of days to add * @return modified date */publicstaticLocalDateaddDaysToLocalDate(LocalDatedate, longnoOfDays) {
returndate != null ? date.plusDays(noOfDays) : null;
}
}publicclassDateDifferenceSnippet {
/** * This function calculates the number of years between two LocalDate objects. * If the result is negative, it returns the absolute value of the difference. * * @param firstTime The first LocalDate object representing the starting date * @param secondTime The second LocalDate object representing the ending date * @return The number of years between the two LocalDate objects as a long data type */publicstaticlonggetYearsDifference(LocalDatefirstTime, LocalDatesecondTime) {
varyearsDifference = ChronoUnit.YEARS.between(firstTime, secondTime);
returnMath.abs(yearsDifference);
}
/** * This function calculates the number of months between two LocalDate objects. * If the result is negative, it returns the absolute value of the difference. * * @param firstTime The first LocalDate object representing the starting date * @param secondTime The second LocalDate object representing the ending date * @return The number of months between the two LocalDate objects as a long data type */publicstaticlonggetMonthsDifference(LocalDatefirstTime, LocalDatesecondTime) {
varmonthsDifference = ChronoUnit.MONTHS.between(firstTime, secondTime);
returnMath.abs(monthsDifference);
}
/** * This function calculates the number of days between two LocalDate objects. * If the result is negative, it returns the absolute value of the difference. * * @param firstTime The first LocalDate object representing the starting date * @param secondTime The second LocalDate object representing the ending date * @return The number of days between the two LocalDate objects as a long data type */publicstaticlonggetDaysDifference(LocalDatefirstTime, LocalDatesecondTime) {
vardaysDifference = ChronoUnit.DAYS.between(firstTime, secondTime);
returnMath.abs(daysDifference);
}
}publicclassBase64DecodeSnippet {
/** * Decodes a Base64 encoded string to the actual representation. * * @param input base64 encoded string * @return decoded string */publicstaticStringdecodeBase64(Stringinput) {
returnnewString(Base64.getDecoder().decode(input.getBytes()));
}
}publicclassBase64EncodeSnippet {
/** * Encodes the input string to a Base64 encoded string. * * @param input string to be encoded * @return base64 encoded string */publicstaticStringencodeBase64(Stringinput) {
returnBase64.getEncoder().encodeToString(input.getBytes());
}
}publicclassListAllFilesSnippet {
/** * Recursively list all the files in directory. * * @param path the path to start the search from * @return list of all files */publicstaticList<File> listAllFiles(Stringpath) {
varall = newArrayList<File>();
varlist = newFile(path).listFiles();
if (list != null) { // In case of access error, list is nullfor (varf : list) {
if (f.isDirectory()) {
all.addAll(listAllFiles(f.getAbsolutePath()));
} else {
all.add(f.getAbsoluteFile());
}
}
}
returnall;
}
}publicclassListDirectoriesSnippet {
/** * List directories. * * @param path the path where to look * @return array of File */publicstaticFile[] listDirectories(Stringpath) {
returnnewFile(path).listFiles(File::isDirectory);
}
}publicclassListFilesInDirectorySnippet {
/** * List files in directory. * * @param folder the path where to look * @return array of File */publicstaticFile[] listFilesInDirectory(Stringfolder) {
returnnewFile(folder).listFiles(File::isFile);
}
}publicclassReadLinesSnippet {
/** * 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 */publicstaticList<String> readLines(Stringfilename) throwsIOException {
returnFiles.readAllLines(Paths.get(filename));
}
}publicclassZipDirectorySnippet {
/** * Zip a complete directory. * * @param srcDirectoryName The path to the directory to be zipped * @param zipFileName The location and name of the zipped file. * @throws IOException if an I/O error occurs * */publicstaticvoidzipDirectory(StringsrcDirectoryName, StringzipFileName) throwsIOException {
varsrcDirectory = newFile(srcDirectoryName);
try (
varfileOut = newFileOutputStream(zipFileName);
varzipOut = newZipOutputStream(fileOut)
) {
zipFile(srcDirectory, srcDirectory.getName(), zipOut);
}
}
/** * Utility function which either zips a single file, or recursively calls itself for * a directory to traverse down to the files contained within it. * * @param fileToZip The file as a resource * @param fileName The actual name of the file * @param zipOut The output stream to which all data is being written * */publicstaticvoidzipFile(FilefileToZip, StringfileName, ZipOutputStreamzipOut)
throwsIOException {
if (fileToZip.isHidden()) { // Ignore hidden files as standardreturn;
}
if (fileToZip.isDirectory()) {
if (fileName.endsWith("/")) {
zipOut.putNextEntry(newZipEntry(fileName)); // To be zipped nextzipOut.closeEntry();
} else {
// Add the "/" mark explicitly to preserve structure while unzipping action is performedzipOut.putNextEntry(newZipEntry(fileName + "/"));
zipOut.closeEntry();
}
varchildren = fileToZip.listFiles();
for (varchildFile : children) { // Recursively apply function to all childrenzipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
}
return;
}
try (
varfis = newFileInputStream(fileToZip) // Start zipping once we know it is a file
) {
varzipEntry = newZipEntry(fileName);
zipOut.putNextEntry(zipEntry);
varbytes = newbyte[1024];
varlength = 0;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
}
}
}publicclassZipFileSnippet {
/** * Zip single file. * * @param srcFilename the filename of the source file * @param zipFilename the filename of the destination zip file * @throws IOException if an I/O error occurs */publicstaticvoidzipFile(StringsrcFilename, StringzipFilename) throwsIOException {
varsrcFile = newFile(srcFilename);
try (
varfileOut = newFileOutputStream(zipFilename);
varzipOut = newZipOutputStream(fileOut);
varfileIn = newFileInputStream(srcFile)
) {
varzipEntry = newZipEntry(srcFile.getName());
zipOut.putNextEntry(zipEntry);
finalvarbytes = newbyte[1024];
intlength;
while ((length = fileIn.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
}
}
}publicclassZipFilesSnippet {
/** * Zip multiples files. * * @param srcFilenames array of source file names * @param zipFilename the filename of the destination zip file * @throws IOException if an I/O error occurs */publicstaticvoidzipFiles(String[] srcFilenames, StringzipFilename) throwsIOException {
try (
varfileOut = newFileOutputStream(zipFilename);
varzipOut = newZipOutputStream(fileOut)
) {
for (StringsrcFilename : srcFilenames) {
varsrcFile = newFile(srcFilename);
try (varfileIn = newFileInputStream(srcFile)) {
varzipEntry = newZipEntry(srcFile.getName());
zipOut.putNextEntry(zipEntry);
finalvarbytes = newbyte[1024];
intlength;
while ((length = fileIn.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
}
}
}
}
}publicclassInputStreamToStringSnippet {
/** * Convert InputStream to String. * * @param inputStream InputStream to convert * @return String */publicstaticStringinputStreamToString(InputStreaminputStream) {
returnnewBufferedReader(newInputStreamReader(inputStream, StandardCharsets.UTF_8))
.lines().collect(Collectors.joining(System.lineSeparator()));
}
}publicclassReadFileSnippet {
/** * Read file using stream and return list of string lines. * * @param fileName file to read * @throws FileNotFoundException if an I/O error occurs */publicstaticList<String> readFile(StringfileName) throwsFileNotFoundException {
try (Stream<String> stream = newBufferedReader(newFileReader(fileName)).lines()) {
returnstream.collect(Collectors.toList());
}
}
}publicclassDiceThrow {
privatestaticRandomrandom = newRandom();
/** * Enum for standardized sided dice (4,6,8,10,12 and 20). */publicenumDiceSides {
FOUR(4), SIX(6), EIGHT(8), TEN(10), TWELVE(12), TWENTY(20);
privatefinalintdiSides;
DiceSides(intdiceSides) {
this.diSides = diceSides;
}
/** * Returns the number of sides of a dice. * * @return int denoting number of sides of a dice */publicintgetDiceSides() {
returnthis.diSides;
}
}
/** * Returns the sum of sides for the given number of sides of each dice. * * @param noOfDice number of dice * @param sides sides of a dice * @return int sum of sides for number of dice */publicstaticintthrowDice(intnoOfDice, DiceSidessides) {
intsum = 0;
for (inti = 0; i < noOfDice; i++) {
sum = sum + (1 + random.nextInt(sides.getDiceSides()));
}
returnsum;
}
}publicclassEloRatingSnippet {
staticfinalintBASE = 400; //Two types are popular - 400 and 480. We will choose 400 herestaticfinalintRATING_ADJUSTMENT_FACTOR = 32; //32 is the standard for Beginner Games/** * Elo Rating Snippet to calculate result after a single match. * * @param firstPlayerRating Rating of the first player. * @param secondPlayerRating Rating of the second player. * @param result Result of the match, always considered with respect to the first player. * 1 indicates a win, 0.5 indicates a draw and 0 indicates a loss. * @return Returns the new rating of the first player. */publicstaticdoublecalculateMatchRating(doublefirstPlayerRating, doublesecondPlayerRating,
doubleresult) {
doubleratingDiff = ((secondPlayerRating - firstPlayerRating) * 1.0) / BASE;
doublelogisticDiff = Math.pow(10, ratingDiff);
doublefirstPlayerExpectedScore = 1.0 / (1 + logisticDiff);
doublefirstPlayerActualScore = result;
doublenewRating = firstPlayerRating + RATING_ADJUSTMENT_FACTOR * (firstPlayerActualScore
- firstPlayerExpectedScore);
returnnewRating;
}
}publicclassEvenOdd {
/** * Returns string denoting number is odd or even. * * @param num To check whether its even or odd * @return string denoting its even or odd */publicstaticStringevenodd(intnum) {
if (num % 2 == 0) {
return"even";
} else {
return"odd";
}
}
}publicclassFactorialSnippet {
/** * Factorial. Works only for small numbers * * @param number for which factorial is to be calculated for * @return factorial */publicstaticintfactorial(intnumber) {
varresult = 1;
for (varfactor = 2; factor <= number; factor++) {
result *= factor;
}
returnresult;
}
/** * Factorial. Example of what the recursive implementation looks like. * * @param number for which factorial is to be calculated for * @return factorial */publicstaticintrecursiveFactorial(intnumber) {
varinitial = 0;
if (number == initial) {
returninitial + 1;
}
returnnumber * recursiveFactorial(number - 1);
}
}publicclassFibonacciSnippet {
/** * Recursive Fibonacci series. Works only for small n and is spectacularly inefficient * * @param n given number * @return fibonacci number for given n */publicstaticintfibonacci(intn) {
if (n <= 1) {
returnn;
} else {
returnfibonacci(n - 1) + fibonacci(n - 2);
}
}
/** * Fibonacci series using dynamic programming. Works for larger ns as well. * * @param n given number * @return fibonacci number for given n */publicstaticintfibonacciBig(intn) {
intprevious = 0;
intcurrent = 1;
for (inti = 0; i < n - 1; i++) {
intt = previous + current;
previous = current;
current = t;
}
returncurrent;
}
/** * Example of what an iterative implementation of Fibonacci looks like. * * @param number given number * @return fibonacci number for given n */publicstaticintiterativeFibonacci(intnumber) {
List<Integer> list = newArrayList<>();
list.add(0);
list.add(1);
for (inti = 2; i < number + 1; i++) {
list.add(list.get(i - 2) + list.get(i - 1));
}
returnlist.get(number);
}
}publicclassGreatestCommonDivisorSnippet {
/** * Greatest common divisor calculation. * * @param a one of the numbers whose gcd is to be computed * @param b other number whose gcd is to be computed * @return gcd of the two numbers */publicstaticintgcd(inta, intb) {
if (b == 0) {
returna;
}
returngcd(b, a % b);
}
}publicclassHaversineFormulaSnippet {
// Radius of sphere on which the points are, in this case Earth.privatestaticfinaldoubleSPHERE_RADIUS_IN_KM = 6372.8;
/** * Haversine formula for calculating distance between two latitude, longitude points. * * @param latA Latitude of point A * @param longA Longitude of point A * @param latB Latitude of point B * @param longB Longitude of point B * @return the distance between the two points. */publicstaticdoublefindHaversineDistance(doublelatA, doublelongA, doublelatB, doublelongB) {
if (!isValidLatitude(latA)
|| !isValidLatitude(latB)
|| !isValidLongitude(longA)
|| !isValidLongitude(longB)) {
thrownewIllegalArgumentException();
}
// Calculate the latitude and longitude differencesvarlatitudeDiff = Math.toRadians(latB - latA);
varlongitudeDiff = Math.toRadians(longB - longA);
varlatitudeA = Math.toRadians(latA);
varlatitudeB = Math.toRadians(latB);
// Calculating the distance as per haversine formulavara = Math.pow(Math.sin(latitudeDiff / 2), 2)
+ Math.pow(Math.sin(longitudeDiff / 2), 2) * Math.cos(latitudeA) * Math.cos(latitudeB);
varc = 2 * Math.asin(Math.sqrt(a));
returnSPHERE_RADIUS_IN_KM * c;
}
// Check for valid latitude valueprivatestaticbooleanisValidLatitude(doublelatitude) {
returnlatitude >= -90 && latitude <= 90;
}
// Check for valid longitude valueprivatestaticbooleanisValidLongitude(doublelongitude) {
returnlongitude >= -180 && longitude <= 180;
}
}publicclassLeastCommonMultipleSnippet {
/** * Least common multiple calculation. * * @param a one of the numbers whose lcm is to be computed * @param b other number whose lcm is to be computed * @return lcm of the two numbers */publicstaticintlcm(inta, intb) {
intmax = a > b ? a : b;
intmin = a < b ? a : b;
for (inti = 1; i <= min; i += 1) {
intprod = max * i;
if (prod % min == 0) {
returnprod;
}
}
returnmax * min;
}
}publicclassLuhnSnippet {
/** * Calculates checksum for a given number with Luhn's algorithm. Works only on non-negative * integers not greater than {@link Long#MAX_VALUE} i.e., all numbers with a maximum of 18 * digits, plus 19-digit-long numbers start with 1..8 (also some with 9, too). For * demonstration purposes, algorithm is not optimized for efficiency. * * @param num number whose checksum is to be calculated * @return checksum value for num * @see <a href="https://patents.google.com/patent/US2950048A">Hans P. LUHN's patent US2950048A</a> * @see <a href="https://en.wikipedia.org/wiki/Luhn_algorithm">Luhn algorithm on Wikipedia</a> */publicstaticintcalculateLuhnChecksum(longnum) {
if (num < 0) {
thrownewIllegalArgumentException("Non-negative numbers only.");
}
finalvarnumStr = String.valueOf(num);
varsum = 0;
varisOddPosition = true;
// Loop on digits of numStr from right to left.for (vari = numStr.length() - 1; i >= 0; i--) {
finalvardigit = Integer.parseInt(Character.toString(numStr.charAt(i)));
finalvarsubstituteDigit = (isOddPosition ? 2 : 1) * digit;
finalvartensPlaceDigit = substituteDigit / 10;
finalvaronesPlaceDigit = substituteDigit % 10;
sum += tensPlaceDigit + onesPlaceDigit;
isOddPosition = !isOddPosition;
}
finalvarchecksumDigit = (10 - (sum % 10)) % 10;
// Outermost modulus handles edge case `num = 0`.returnchecksumDigit;
}
}publicclassNaturalNumberBinaryConversionSnippet {
/** * Convert natural number to binary string. Only supports positive integers.Throws exception * for negative integers * * @param naturalNumber given number * @return Binary string representation of naturalNumber */publicstaticStringtoBinary(longnaturalNumber) {
if (naturalNumber < 0) {
thrownewNumberFormatException("Negative Integer, this snippet only accepts "
+ "positive integers");
}
if (naturalNumber == 0) {
return"0";
}
finalStack<Long> binaryBits =
Stream.iterate(naturalNumber, n -> n > 0, n -> n / 2).map(n -> n % 2)
.collect(Stack::new, Stack::push, Stack::addAll);
returnStream.generate(binaryBits::pop)
.limit(binaryBits.size()).map(String::valueOf).collect(Collectors.joining());
}
/** * Convert binary string representation to Long valued Integer. Throws exception if input * string contains characters other than '0' and '1' * * @param binary given number * @return Unsigned Long value for the binary number */publicstaticLongfromBinary(Stringbinary) {
binary.chars().filter(c -> c != '0' && c != '1').findFirst().ifPresent(in -> {
thrownewNumberFormatException(
"Binary string contains values other than '0' and '1'");
});
returnIntStream.range(0, binary.length())
.filter(in -> binary.charAt(binary.length() - 1 - in) == '1')
.mapToLong(in -> ((long) 0b1) << in).sum();
}
}publicclassPerformLotterySnippet {
/** * Generate random lottery numbers. * * @param numNumbers how many performLottery numbers are available (e.g. 49) * @param numbersToPick how many numbers the player needs to pick (e.g. 6) * @return array with the random numbers */publicstaticInteger[] performLottery(intnumNumbers, intnumbersToPick) {
varnumbers = newArrayList<Integer>();
for (vari = 0; i < numNumbers; i++) {
numbers.add(i + 1);
}
Collections.shuffle(numbers);
returnnumbers.subList(0, numbersToPick).toArray(newInteger[numbersToPick]);
}
}publicclassPrimeNumberSnippet {
/** * Checks if given number is a prime number. Prime number is a number that is greater than 1 and * divided by 1 or itself only Credits: https://en.wikipedia.org/wiki/Prime_number * * @param number number to check prime * @return true if prime */publicstaticbooleanisPrime(intnumber) {
//if number < 2 its not a prime numberif (number < 2) {
returnfalse;
}
// 2 and 3 are prime numbersif (number < 3) {
returntrue;
}
// check if n is a multiple of 2if (number % 2 == 0) {
returnfalse;
}
// if not, then just check the oddsfor (vari = 3; i * i <= number; i += 2) {
if (number % i == 0) {
returnfalse;
}
}
returntrue;
}
}publicclassRandomNumber {
privateRandomNumber() {}
privatestaticRandomrandom = newRandom();
/** * Return a random number between two given numbers. * * @param start Starting point to find the random number * @param end Ending point to find the random number * @return Number denoting the random number generated */publicstatic <TextendsNumber> NumbergetRandomNumber(Tstart, Tend) {
if (startinstanceofByte && endinstanceofByte) {
return (byte) (start.byteValue()
+ random.nextInt(end.byteValue() - start.byteValue() + 1));
} elseif (startinstanceofShort && endinstanceofShort) {
return (short) (start.shortValue()
+ random.nextInt(end.shortValue() - start.shortValue() + 1));
} elseif (startinstanceofInteger && endinstanceofInteger) {
returnstart.intValue()
+ random.nextInt(end.intValue() - start.intValue() + 1);
} elseif (startinstanceofLong && endinstanceofLong) {
returnstart.longValue()
+ (long) (random.nextDouble() * end.longValue() - start.longValue() + 1);
} elseif (startinstanceofFloat && endinstanceofFloat) {
returnstart.floatValue()
+ random.nextFloat() * (end.floatValue() - start.floatValue());
} elseif (startinstanceofDouble && endinstanceofDouble) {
returnstart.doubleValue()
+ random.nextDouble() * (end.doubleValue() - start.doubleValue());
} else {
thrownewIllegalArgumentException("Invalid Numbers As Arguments "
+ start.getClass() + " and " + end.getClass());
}
}
}publicclassSquareRoot {
/** * Returns square root of a number. * * @param num To find SquareRoot * @param p precision till how many decimal numbers we want accurate ans */publicstaticdoublesqrt(intnum, intp) {
intstart = 0;
intend = num;
doubleroot = 0.0;
while (start <= end) {
intmid = start + (end - start) / 2;
if ((mid * mid) > num) {
end = mid - 1;
} elseif ((mid * mid) < num) {
start = mid + 1;
} else {
returnmid;
}
}
doubleincr = 0.1;
for (inti = 0; i < p; i++) {
while (root * root < num) {
root = root + incr;
}
root = root - incr;
incr = incr / 10;
}
returnroot;
}
}publicclassCaptureScreenSnippet {
/** * Capture screenshot and save it to PNG file. Credits: https://viralpatel.net/blogs/how-to-take-screen-shots-in-java-taking-screenshots-java/ * * @param filename the name of the file * @throws AWTException if the platform configuration does not allow low-level input control * @throws IOException if an I/O error occurs */publicstaticvoidcaptureScreen(Stringfilename) throwsAWTException, IOException {
varscreenSize = Toolkit.getDefaultToolkit().getScreenSize();
varscreenRectangle = newRectangle(screenSize);
varrobot = newRobot();
varimage = robot.createScreenCapture(screenRectangle);
ImageIO.write(image, "png", newFile(filename));
}
}publicclassHttpGetSnippet {
/** * Performs HTTP GET request. * * @param uri the URI of the connection * @return response object * @throws Exception i/o error, interruption error, etc */publicstaticHttpResponse<String> httpGet(Stringuri) throwsException {
varclient = HttpClient.newHttpClient();
varrequest = HttpRequest.newBuilder()
.uri(URI.create(uri))
.build();
returnclient.send(request, HttpResponse.BodyHandlers.ofString());
}
}publicclassHttpPostSnippet {
/** * Performs HTTP POST request. Credits https://stackoverflow.com/questions/3324717/sending-http-post-request-in-java * * @param address the URL of the connection in String format, like "http://www.google.com" * @param arguments the body of the POST request, as a HashMap * @return response object * @throws IOException if an I/O error occurs * @throws InterruptedException if the operation is interrupted */publicstaticHttpResponse<String> httpPost(Stringaddress, HashMap<String, String> arguments)
throwsIOException, InterruptedException {
varsj = newStringJoiner("&");
for (varentry : arguments.entrySet()) {
sj.add(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8) + "="
+ URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
}
varout = sj.toString().getBytes(StandardCharsets.UTF_8);
varrequest = HttpRequest.newBuilder()
.uri(URI.create(address))
.headers("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofByteArray(out))
.build();
returnHttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
}
}publicclassAnagramSnippet {
/** * Checks if two words are anagrams (contains same characters with same frequency in any order). * * @param s1 The first string to be checked * @param s2 The second string to be checked * @return true if they are anagrams of each other */publicstaticbooleanisAnagram(Strings1, Strings2) {
varl1 = s1.length();
varl2 = s2.length();
if (l1 != l2) {
returnfalse;
}
vararr1 = newint[256];
vararr2 = newint[256];
for (vari = 0; i < l1; i++) {
arr1[s1.charAt(i)]++;
arr2[s2.charAt(i)]++;
}
returnArrays.equals(arr1, arr2);
}
}publicclassCommonLettersSnippet {
/** * Find Common Characters inside given two strings. * * @param firstStr first string * @param secondStr second string * @return Common Characters. */publicstaticStringgetCommonLetters(StringfirstStr, StringsecondStr) {
Set<String> commonLetters = newHashSet<>();
for (CharactercurrentCharacter : firstStr.toCharArray()) {
if (isCommonLetter(secondStr, currentCharacter)) {
commonLetters.add(currentCharacter.toString());
}
}
returnString.join(" ", commonLetters);
}
privatestaticbooleanisCommonLetter(Stringstr, Charactercharacter) {
returnstr.contains(character.toString()) && Character.isLetter(character);
}
}publicclassCompareVersionSnippet {
privatestaticfinalStringEXTRACT_VERSION_REGEX = ".*?((?<!\\w)\\d+([.-]\\d+)*).*";
/** * Compares two version strings. * Credits: https://stackoverflow.com/a/6702000/6645088 and https://stackoverflow.com/a/44592696/6645088 * * @param v1 the first version string to compare * @param v2 the second version string to compare * @return the value {@code 0} if the two strings represent same versions; * a value less than {@code 0} if {@code v1} is greater than {@code v2}; and * a value greater than {@code 0} if {@code v2} is greater than {@code v1} */publicstaticintcompareVersion(Stringv1, Stringv2) {
varcomponents1 = getVersionComponents(v1);
varcomponents2 = getVersionComponents(v2);
intlength = Math.max(components1.length, components2.length);
for (inti = 0; i < length; i++) {
Integerc1 = i < components1.length ? Integer.parseInt(components1[i]) : 0;
Integerc2 = i < components2.length ? Integer.parseInt(components2[i]) : 0;
intresult = c1.compareTo(c2);
if (result != 0) {
returnresult;
}
}
return0;
}
privatestaticString[] getVersionComponents(Stringversion) {
returnversion.replaceAll(EXTRACT_VERSION_REGEX, "$1").split("\\.");
}
}publicclassDuplicateCharacterSnippet {
/** * Remove Duplicate Characters from a string. * * @param str The string to be processed * @return A string with no duplicate characters */publicstaticStringremoveDuplicateCharacters(Stringstr) {
char[] charsOfStr = str.toCharArray();
Set<String> uniqueCharacters = newHashSet<>();
for (charcharacter : charsOfStr) {
uniqueCharacters.add(String.valueOf(character));
}
returnString.join("", uniqueCharacters);
}
}publicclassLevenshteinDistanceSnippet {
/** * Find the Levenshtein distance between two words. https://en.wikipedia.org/wiki/Levenshtein_distance * * @param word1 first word * @param word2 second word * @return distance */publicstaticintfindLevenshteinDistance(Stringword1, Stringword2) {
// If word2 is empty, removingint[][] ans = newint[word1.length() + 1][word2.length() + 1];
for (inti = 0; i <= word1.length(); i++) {
ans[i][0] = i;
}
// if word1 is empty, addingfor (inti = 0; i <= word2.length(); i++) {
ans[0][i] = i;
}
// None is emptyfor (inti = 1; i <= word1.length(); i++) {
for (intj = 1; j <= word2.length(); j++) {
intmin = Math.min(Math.min(ans[i][j - 1], ans[i - 1][j]), ans[i - 1][j - 1]);
ans[i][j] = word1.charAt(i - 1) == word2.charAt(j - 1) ? ans[i - 1][j - 1] : min + 1;
}
}
returnans[word1.length()][word2.length()];
}
}publicclassLindenmayerSystemSnippet {
/** * Generates an L-system string based on axiom, production rules, and a number of iterations. * * @param axiom initial string to begin the L-system * @param productionRules map of character rules where each symbol can be replaced with a string * @param iterations number of iterations to apply the production rules * @return the generated string after all iterations */publicstaticStringgenerateLindenmayerSystem(
Stringaxiom,
Map<Character, String> productionRules,
intiterations
) {
Stringcurrent = axiom;
for (inti = 0; i < iterations; i++) {
StringBuildernextIteration = newStringBuilder(current.length() * 2);
// Replace each symbol with the corresponding production rule or the symbol itselfcurrent.chars()
.mapToObj(c -> (char) c)
.forEach(symbol ->
nextIteration.append(
productionRules.getOrDefault(symbol, String.valueOf(symbol))
)
);
current = nextIteration.toString();
}
returncurrent;
}
}publicclassMaxCharacterCountSnippet {
/** * The maximum count of times a specific character appears in a string. * * @param str َA specific string * @param character A specific character * @return the maximum count of one character */publicstaticintgetMaxCharacterCount(Stringstr, charcharacter) {
intcharacterCount = 0;
intmaxCharacterCount = 0;
for (inti = 0; i < str.length(); i++) {
if ((str.charAt(i)) == character) {
characterCount++;
maxCharacterCount = Math.max(maxCharacterCount, characterCount);
} else {
characterCount = 0;
}
}
returnmaxCharacterCount;
}
}publicclassPalindromCheckSnippet {
/** * Checks if given string is palindrome (same forward and backward). Skips non-letter characters * Credits: https://github.com/kousen/java_8_recipes * * @param s string to check * @return true if palindrome */publicstaticbooleanisPalindrome(Strings) {
for (inti = 0, j = s.length() - 1; i < j; i++, j--) {
while (i < j && !Character.isLetter(s.charAt(i))) {
i++;
}
while (i < j && !Character.isLetter(s.charAt(j))) {
j--;
}
if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) {
returnfalse;
}
}
returntrue;
}
}publicclassReverseStringSnippet {
/** * Reverse string. * * @param s the string to reverse * @return reversed string */publicstaticStringreverseString(Strings) {
returnnewStringBuilder(s).reverse().toString();
}
}publicclassStringToDateSnippet {
/** * Convert string to date. * * @param date the date string * @param format expected date format * @return Date * @throws ParseException in case of an unparseable date string */publicstaticDatestringToDate(Stringdate, Stringformat) throwsParseException {
varsimpleDateFormat = newSimpleDateFormat(format);
returnsimpleDateFormat.parse(date);
}
}publicclassKMPSubstringSearchSnippet {
/** * Implements the Knuth-Morris-Pratt (KMP) algorithm to find the index of the first occurrence of a substring in a given text. * * @param text The text in which the substring is to be searched. * @param pattern The substring pattern to search for. * @return The index of the first occurrence of the pattern in the text, or -1 if the pattern is not found. */publicstaticintkmpSearch(Stringtext, Stringpattern) {
if (pattern == null || pattern.length() == 0) {
return0; // Trivial case: empty pattern
}
int[] lps = computeLPSArray(pattern);
inti = 0; // index for textintj = 0; // index for patternwhile (i < text.length()) {
if (pattern.charAt(j) == text.charAt(i)) {
i++;
j++;
}
if (j == pattern.length()) {
returni - j; // Found pattern at index (i - j)
} elseif (i < text.length() && pattern.charAt(j) != text.charAt(i)) {
if (j != 0) {
j = lps[j - 1]; // Use the LPS array to skip characters
} else {
i++; // If no match and j is 0, move to the next character in text
}
}
}
return -1; // Pattern not found
}
/** * Computes the LPS (Longest Prefix Suffix) array for the pattern, which indicates the longest proper prefix which is also a suffix. * * @param pattern The pattern for which the LPS array is to be computed. * @return The LPS array. */privatestaticint[] computeLPSArray(Stringpattern) {
intlength = 0;
inti = 1;
int[] lps = newint[pattern.length()];
lps[0] = 0; // LPS for the first character is always 0while (i < pattern.length()) {
if (pattern.charAt(i) == pattern.charAt(length)) {
length++;
lps[i] = length;
i++;
} else {
if (length != 0) {
length = lps[length - 1]; // Fall back to the previous LPS value
} else {
lps[i] = 0;
i++;
}
}
}
returnlps;
}
}publicclassFormatBytesSnippet {
/** * Convert bytes into Human readable form. * * @param bytes The value in bytes needed to be converted * @return String the converted human-readable form */publicstaticStringformatBytes(longbytes) {
doublekb = 1024;
doublemb = kb * 1024;
doublegb = mb * 1024;
doubletb = gb * 1024;
if ((bytes >= 0) && (bytes < kb)) {
returnbytes + " B";
} elseif ((bytes >= kb) && (bytes < mb)) {
returnString.format("%.2f KB", bytes / kb);
} elseif ((bytes >= mb) && (bytes < gb)) {
returnString.format("%.2f MB", bytes / mb);
} elseif ((bytes >= gb) && (bytes < tb)) {
returnString.format("%.2f GB", bytes / gb);
} elseif (bytes >= tb) {
returnString.format("%.2f TB", bytes / tb);
} else {
return"Invalid Input";
}
}
}publicclassThreadSnippet {
/** * 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. */publicstaticThreadcreateThread(Runnabletask) {
returnnewThread(task);
}
}publicclassThreadPool {
/** * <p>Creates pool of threads. Where the pool is the size of the number of processors * available to the Java virtual machine.</p> * * @return the newly created thread pool */publicstaticExecutorServicecreateFixedThreadPool() {
returnExecutors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
}
}publicclassDammSnippet {
/** * Private constructor to prevent instantiation of utility class. */privateDammSnippet() {
thrownewUnsupportedOperationException("Utility class - instantiation is not allowed.");
}
privatestaticfinalint[][] matrix = newint[][] {
{ 0, 3, 1, 7, 5, 9, 8, 6, 4, 2 },
{ 7, 0, 9, 2, 1, 5, 4, 8, 6, 3 },
{ 4, 2, 0, 6, 8, 7, 1, 3, 5, 9 },
{ 1, 7, 5, 0, 9, 8, 3, 4, 2, 6 },
{ 6, 1, 2, 3, 0, 4, 5, 9, 7, 8 },
{ 3, 6, 7, 4, 2, 0, 9, 5, 8, 1 },
{ 5, 8, 6, 9, 7, 2, 0, 1, 3, 4 },
{ 8, 9, 4, 5, 3, 6, 2, 0, 1, 7 },
{ 9, 4, 3, 8, 6, 1, 7, 2, 0, 5 },
{ 2, 5, 8, 1, 4, 3, 6, 7, 9, 0 }
};
publicstaticintcalculateCheckSumDigit(Stringnumber) {
if (number == null || number.isEmpty()) {
thrownewIllegalArgumentException("Input number cannot be null or empty.");
}
intinterim = 0;
for (intindex = 0; index < number.length(); index++) {
charcurrCh = number.charAt(index);
if (!Character.isDigit(currCh)) {
thrownewIllegalArgumentException("Input number contains invalid characters: " + number);
}
intcurrentIndex = currCh - '0';
interim = matrix[interim][currentIndex];
}
returninterim;
}
publicstaticintcalculateCheckSumDigit(intnumber) {
returncalculateCheckSumDigit(String.valueOf(number));
}
publicstaticintcalculateCheckSumDigit(longnumber) {
returncalculateCheckSumDigit(String.valueOf(number));
}
publicstaticStringgenerateCheckSum(Stringnumber) {
intcheckSumDigit = calculateCheckSumDigit(number);
returnnumber + checkSumDigit;
}
publicstaticintgenerateCheckSum(intnumber) {
intcheckSumDigit = calculateCheckSumDigit(number);
return (number * 10) + checkSumDigit;
}
publicstaticlonggenerateCheckSum(longnumber) {
intcheckSumNumber = calculateCheckSumDigit(number);
return (number * 10) + checkSumNumber;
}
publicstaticbooleanvalidate(Stringnumber) {
returncalculateCheckSumDigit(number) == 0;
}
publicstaticbooleanvalidate(intnumber) {
returncalculateCheckSumDigit(number) == 0;
}
publicstaticbooleanvalidate(longnumber) {
returncalculateCheckSumDigit(number) == 0;
}
}