Java Snippets #

Build status

Inspired by 30 seconds of code, this is a collection of reusable tested Java code snippets.

How to contribute #

Update the sample application with the snippet and add a test for it. After proving that it works update this README.md.

Table of Contents #

Array #

File #

Math #

Media #

String #

Array #

Generic two array concatenation #

    public static <T> T[] arrayConcat(T[] first, T[] second) {
        T[] result = Arrays.copyOf(first, first.length + second.length);
        System.arraycopy(second, 0, result, first.length, second.length);
        return result;
    }

⬆ back to top

Generic N array concatenation #

    public static <T> T[] nArrayConcat(T[] first, T[]... rest) {
        int totalLength = first.length;
        for (T[] array : rest) {
            totalLength += array.length;
        }
        T[] result = Arrays.copyOf(first, totalLength);
        int offset = first.length;
        for (T[] array : rest) {
            System.arraycopy(array, 0, result, offset, array.length);
            offset += array.length;
        }
        return result;
    }

⬆ back to top

File #

List directories #

    public static File[] listDirectories(String path) {
        return new File(path).listFiles(File::isDirectory);
    }

⬆ back to top

Read lines from file to string list #

    public static List<String> readLines(String filename) throws IOException {
        return Files.readAllLines(new File(filename).toPath());
    }

⬆ back to top

Math #

Fibonacci #

    public static int fibonacci(int n) {
        if (n <= 1) return n;
        else return fibonacci(n-1) + fibonacci(n-2);
    }

⬆ back to top

Factorial #

    public static int factorial(int number) {
        int result = 1;
        for (int factor = 2; factor <= number; factor++) {
            result *= factor;
        }
        return result;
    }

⬆ back to top

Media #

Capture screen #

    public static void captureScreen(String filename) throws AWTException, IOException {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Rectangle screenRectangle = new Rectangle(screenSize);
        Robot robot = new Robot();
        BufferedImage image = robot.createScreenCapture(screenRectangle);
        ImageIO.write(image, "png", new File(filename));
    }

⬆ back to top

String #

Reverse string #

    public static String reverseString(String s) {
        return new StringBuilder(s).reverse().toString();
    }

⬆ back to top

String to date #

    public static Date stringToDate(String date, String format) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        return simpleDateFormat.parse(date);
    }

⬆ back to top