Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
3

30-seconds-of-java

> 编程语言
Open source

Collection of reusable tested Java 21 compatible code snippets that you can understand in 30 seconds or less.

1.1K stars0 likes2 views
WebsiteGitHub

About

Collection of reusable tested Java 21 compatible code snippets that you can understand in 30 seconds or less.


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

30 Seconds of Java - Essential Code Snippets Library for Java Developers

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.

Algorithm

Binary Search In 2d Array

…

Bubble Sort

java
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;
        }
      }
    }
  }
}

Counting Sort

java
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;
    }
  }
}

Cycle Sort

java
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;
    }
  }
}

Linear Search In 2d Array

…

Merge Sort

…

Selection Sort

java
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;
  }
}

Array Concat

java
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;
  }
}

Array Mean

java
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;
  }
}

Array Median

java
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;
  }
}

Array Mode In Place

java
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;
  }
}

Array Mode

…

Array Sum

java
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();
  }
}

Find Max

java
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);
  }
}

Find Min

java
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);
  }
}

Multi Array Concatenation

…

Reverse Array

…

Get All Methods

java
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());
  }
}

Safe Cast

java
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();
  }
}

Get All Public Field Names

java
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());
  }
}

Date

Add Days To Date

…

Date Difference

…

Encoding

Base64Decode

java
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()));
  }
}

Base64Encode

java
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());
  }
}

File

List All Files

…

List Directories

java
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);
  }
}

List Files In Directory

java
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);
  }
}

Read Lines

java
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));
  }
}

Zip Directory

…

Zip File

…

Zip Files

…

I/O

InputStream To String

java
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()));
  }
}

Read File Snippet

java
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());
    }
  }
}

System

Get Environment Variable Or Default

java
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);
  }
}

Math

Dice Throw

…

Natural Number Binary Conversion

…

Square Root

…

HTTP POST

…

String

Anagram

…

Compare Version

java
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);
  }
}

Levenshtein Distance

…

Max Character Count

…

Thread

Thread Pool

Thread

java
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);
  }
}
java
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());
  }
}

Damm Algorithm

…

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Javaawesome-listhacktoberfestjavasnippets

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言