Skip to content

Collection of reusable tested Java code snippets

License

Notifications You must be signed in to change notification settings

cyber33/java-snippets

Repository files navigation

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

Algorithm

Array

File

Math

Media

Networking

String

Algorithm

Quicksort

publicstaticvoidquickSort(int[] arr, intleft, intright){intpivotIndex = left + (right - left) / 2; intpivotValue = arr[pivotIndex]; inti = left, j = right; while (i <= j){while (arr[i] < pivotValue){i++} while (arr[j] > pivotValue){j--} if (i <= j){inttmp = 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)} } }

⬆ back to top

Array

Generic two array concatenation

publicstatic <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); returnresult}

⬆ back to top

Generic N array concatenation

publicstatic <T> T[] nArrayConcat(T[] first, T[]... rest){inttotalLength = first.length; for (T[] array : rest){totalLength += array.length} T[] result = Arrays.copyOf(first, totalLength); intoffset = first.length; for (T[] array : rest){System.arraycopy(array, 0, result, offset, array.length); offset += array.length} returnresult}

⬆ back to top

File

List directories

publicstaticFile[] listDirectories(Stringpath){returnnewFile(path).listFiles(File::isDirectory)}

⬆ back to top

List files in directory

publicstaticFile[] listFilesInDirectory(finalFilefolder){returnfolder.listFiles(File::isFile)}

⬆ back to top

List files in directory recursively

publicstaticList<File> listAllFiles(Stringpath){List<File> all = newArrayList<>(); File[] list = newFile(path).listFiles(); if (list != null){// In case of access error, list is nullfor (Filef : list){if (f.isDirectory()){all.addAll(listAllFiles(f.getAbsolutePath()))} else{all.add(f.getAbsoluteFile())} } } returnall}

⬆ back to top

Read lines from file to string list

publicstaticList<String> readLines(Stringfilename) throwsIOException{returnFiles.readAllLines(newFile(filename).toPath())}

⬆ back to top

Zip file

publicstaticvoidzipFile(StringsrcFilename, StringzipFilename) throwsIOException{FilesrcFile = newFile(srcFilename); try ( FileOutputStreamfileOut = newFileOutputStream(zipFilename); ZipOutputStreamzipOut = newZipOutputStream(fileOut); FileInputStreamfileIn = newFileInputStream(srcFile); ){ZipEntryzipEntry = newZipEntry(srcFile.getName()); zipOut.putNextEntry(zipEntry); finalbyte[] bytes = newbyte[1024]; intlength; while ((length = fileIn.read(bytes)) >= 0){zipOut.write(bytes, 0, length)} } }

Zip multiple files

publicstaticvoidzipFiles(String[] srcFilenames, StringzipFilename) throwsIOException{try ( FileOutputStreamfileOut = newFileOutputStream(zipFilename); ZipOutputStreamzipOut = newZipOutputStream(fileOut); ){for (inti=0; i<srcFilenames.length; i++){FilesrcFile = newFile(srcFilenames[i]); try (FileInputStreamfileIn = newFileInputStream(srcFile)){ZipEntryzipEntry = newZipEntry(srcFile.getName()); zipOut.putNextEntry(zipEntry); finalbyte[] bytes = newbyte[1024]; intlength; while ((length = fileIn.read(bytes)) >= 0){zipOut.write(bytes, 0, length)} } } } }

⬆ back to top

Math

Fibonacci

publicstaticintfibonacci(intn){if (n <= 1) returnn; elsereturnfibonacci(n-1) + fibonacci(n-2)}

⬆ back to top

Factorial

publicstaticintfactorial(intnumber){intresult = 1; for (intfactor = 2; factor <= number; factor++){result *= factor} returnresult}

⬆ back to top

Lottery

publicstaticInteger[] performLottery(intnumNumbers, intnumbersToPick){List<Integer> numbers = newArrayList<>(); for(inti = 0; i < numNumbers; i++){numbers.add(i+1)} Collections.shuffle(numbers); returnnumbers.subList(0, numbersToPick).toArray(newInteger[numbersToPick])}

⬆ back to top

Media

Capture screen

publicstaticvoidcaptureScreen(Stringfilename) throwsAWTException, IOException{DimensionscreenSize = Toolkit.getDefaultToolkit().getScreenSize(); RectanglescreenRectangle = newRectangle(screenSize); Robotrobot = newRobot(); BufferedImageimage = robot.createScreenCapture(screenRectangle); ImageIO.write(image, "png", newFile(filename))}

⬆ back to top

Networking

HTTP GET

publicstaticinthttpGet(URLaddress) throwsIOException{HttpURLConnectioncon = (HttpURLConnection) address.openConnection(); returncon.getResponseCode()}

⬆ back to top

String

Palindrome check

publicstaticbooleanisPalindrome(Strings){StringBuildersb = newStringBuilder(); for (charc : s.toCharArray()){if (Character.isLetter(c)){sb.append(c)} } Stringforward = sb.toString().toLowerCase(); Stringbackward = sb.reverse().toString().toLowerCase(); returnforward.equals(backward)}

⬆ back to top

Reverse string

publicstaticStringreverseString(Strings){returnnewStringBuilder(s).reverse().toString()}

⬆ back to top

String to date

publicstaticDatestringToDate(Stringdate, Stringformat) throwsParseException{SimpleDateFormatsimpleDateFormat = newSimpleDateFormat(format); returnsimpleDateFormat.parse(date)}

⬆ back to top

About

Collection of reusable tested Java code snippets

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Java100.0%