Inspired by 30 seconds of code, this is a collection of reusable tested Java code snippets.
Update the sample application with the snippet and add a test for it. After proving that it works update this README.md.
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;
}
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;
}
public static File[] listDirectories(String path) {
return new File(path).listFiles(File::isDirectory);
}
public static List<String> readLines(String filename) throws IOException {
return Files.readAllLines(new File(filename).toPath());
}
public static int fibonacci(int n) {
if (n <= 1) return n;
else return fibonacci(n-1) + fibonacci(n-2);
}
public static int factorial(int number) {
int result = 1;
for (int factor = 2; factor <= number; factor++) {
result *= factor;
}
return result;
}
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));
}
public static String reverseString(String s) {
return new StringBuilder(s).reverse().toString();
}
public static Date stringToDate(String date, String format) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
return simpleDateFormat.parse(date);
}