- Notifications
You must be signed in to change notification settings - Fork0
Collection of reusable tested Java 11 compatible code snippets that you can understand in 30 seconds or less.
License
eimanip/30-seconds-of-java
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Inspired by30 seconds of code, this is a collection of reusabletested Java 11 compatible code snippets that you can understand in 30 seconds or less.
In general, we are interested in well implemented standalone code snippets. There are some tasks that we would like tosee implemented in theissue list. Please raise a new issueif there's an interesting snippet you would like to see in this library but can't implement yourself.
For new snippets the general implementation steps are:
- Create new class inside section-package for example
algorithm.BubbleSortSnippet.java
with the new code snippet. - Add a test for the new code snippet in
algorithm.BubbleSortSnippetTest.java
. - If you want to create new section then create new package, class and tests for it.
- Finally, insert the new snippet into this
README.md
. - Submit pull request against
master
branch.
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); } } }
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; } } } }
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; } }
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; }
publicstatic <T>T[]nArrayConcat(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; }
publicstatic <T>booleanallEqual(T[]arr) {returnArrays.stream(arr).distinct().count() ==1; }
publicstaticintfindMax(int[]arr) {returnArrays.stream(arr).reduce(Integer.MIN_VALUE,Integer::max); }
publicstaticFile[]listDirectories(Stringpath) {returnnewFile(path).listFiles(File::isDirectory); }
publicstaticFile[]listFilesInDirectory(finalFilefolder) {returnfolder.listFiles(File::isFile); }
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; }
publicstaticList<String>readLines(Stringfilename)throwsIOException {returnFiles.readAllLines(newFile(filename).toPath()); }
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); } } }
publicstaticvoidzipFiles(String[]srcFilenames,StringzipFilename)throwsIOException {try (varfileOut =newFileOutputStream(zipFilename);varzipOut =newZipOutputStream(fileOut); ) {for (vari=0;i<srcFilenames.length;i++) {varsrcFile =newFile(srcFilenames[i]);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); } } } } }
publicstaticintfibonacci(intn) {if (n <=1) {returnn; }else {returnfibonacci(n -1) +fibonacci(n -2); } }
publicstaticintfactorial(intnumber) {varresult =1;for (varfactor =2;factor <=number;factor++) {result *=factor; }returnresult; }
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]); }
publicstaticintgcd(inta,intb) {if (b ==0)returna;returngcd(b,a %b); }
publicstaticbooleanisPrime(intnumber) {if (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; }
publicstaticvoidcaptureScreen(Stringfilename)throwsAWTException,IOException {varscreenSize =Toolkit.getDefaultToolkit().getScreenSize();varscreenRectangle =newRectangle(screenSize);varrobot =newRobot();varimage =robot.createScreenCapture(screenRectangle);ImageIO.write(image,"png",newFile(filename)); }
publicstaticHttpResponse<String>httpGet(Stringuri)throwsException {varclient =HttpClient.newHttpClient();varrequest =HttpRequest.newBuilder() .uri(URI.create(uri)) .build();returnclient.send(request,BodyHandlers.ofString()); }
publicstaticHttpResponse<String>httpPost(Stringaddress,HashMap<String,String>arguments)throwsIOException,InterruptedException {varsj =newStringJoiner("&");for(varentry :arguments.entrySet()) {sj.add(URLEncoder.encode(entry.getKey(),"UTF-8") +"=" +URLEncoder.encode(entry.getValue(),"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(BodyPublishers.ofByteArray(out)) .build();returnHttpClient.newHttpClient().send(request,BodyHandlers.ofString()); }
publicstaticbooleanisPalindrome(Strings) {varsb =newStringBuilder();for (varc :s.toCharArray()) {if (Character.isLetter(c)) {sb.append(c); } }varforward =sb.toString().toLowerCase();varbackward =sb.reverse().toString().toLowerCase();returnforward.equals(backward); }
publicstaticStringreverseString(Strings) {returnnewStringBuilder(s).reverse().toString(); }
publicstaticDatestringToDate(Stringdate,Stringformat)throwsParseException {varsimpleDateFormat =newSimpleDateFormat(format);returnsimpleDateFormat.parse(date); }
publicbooleanisAnagram(Strings1,Strings2) {varl1 =s1.length();varl2 =s2.length();vararr1 =newint[256];vararr2 =newint[256];if (l1 !=l2) {returnfalse; }for (vari =0;i <l1;i++) {arr1[s1.charAt(i)]++;arr2[s2.charAt(i)]++; }returnArrays.equals(arr1,arr2); }
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()]; }
publicstaticList<String>getAllMethods(finalClass<?>cls) {varlist =newArrayList<String>();for (varmethod :cls.getDeclaredMethods()) {list.add(method.getName()); }returnlist; }
publicstaticList<String>getAllFieldNames(finalClass<?>cls) {returnArrays.stream(cls.getFields()) .map(Field::getName) .collect(Collectors.toList()); }
publicstaticObjectcreateObject(Stringcls)throwsNoSuchMethodException,IllegalAccessException,InvocationTargetException,InstantiationException,ClassNotFoundException {varobjectClass =Class.forName(cls);varobjectConstructor =objectClass.getConstructor();returnobjectConstructor.newInstance(); }
publicstaticList<String>readFile(StringfileName)throwsFileNotFoundException {try (Stream<String>stream =newBufferedReader(newFileReader(fileName)).lines()) {returnstream.collect(Collectors.toList()); } }
publicstaticStringinputStreamToString(InputStreaminputStream)throwsIOException {try (varreader =newBufferedReader(newInputStreamReader(inputStream))) {varstringBuilder =newStringBuilder();vardata =reader.read();while (data != -1) {stringBuilder.append((char)data);data =reader.read(); }returnstringBuilder.toString(); } }
publicstaticExecutorServicecreateFixedThreadPool() {returnExecutors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); }
About
Collection of reusable tested Java 11 compatible code snippets that you can understand in 30 seconds or less.
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Languages
- Java100.0%