Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

License

NotificationsYou must be signed in to change notification settings

eimanip/30-seconds-of-java

 
 

Repository files navigation

Java CI with GradleJoin the chat at https://gitter.im/iluwatar/30-seconds-of-java

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.

How to contribute

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 examplealgorithm.BubbleSortSnippet.java with the new code snippet.
  • Add a test for the new code snippet inalgorithm.BubbleSortSnippetTest.java.
  • If you want to create new section then create new package, class and tests for it.
  • Finally, insert the new snippet into thisREADME.md.
  • Submit pull request againstmaster branch.

Table of Contents

Algorithm

Quicksortlink
Bubblesortlink
Selectionsortlink

Array

Generic two array concatenationlink
Generic N array concatenationlink
Check if all elements of array are equallink
Find maximum integer from the arraylink

File

List directorieslink
List files in directorylink
List files in directory recursivelylink
Read lines from file to string listlink
Zip filelink
Zip multiple fileslink

Math

Factoriallink
Fibonaccilink
Lotterylink
Greatest Common Divisorlink
Primelink

Media

Capture screenlink

Networking

HTTP GETlink
HTTP POSTlink

String

Palindrome checklink
Reverse stringlink
String to datelink
Anagram Checklink
Find Levenshtein distancelink

Class

Get methods namelink
Get fields namelink
Create objectlink

I/O

Read file by streamlink
InputStream to Stringlink

Thread

Create pool of threadslink

Algorithm

Quicksort

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

Bubblesort

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

Selectionsort

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

Array

Generic two array concatenation

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

Generic N array concatenation

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

Check if all elements of array are equal

publicstatic <T>booleanallEqual(T[]arr) {returnArrays.stream(arr).distinct().count() ==1;  }

Find maximum integer from the array

publicstaticintfindMax(int[]arr) {returnArrays.stream(arr).reduce(Integer.MIN_VALUE,Integer::max);  }

File

List directories

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

List files in directory

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

List files in directory recursively

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

Read lines from file to string list

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

Zip file

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

Zip multiple files

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

Math

Fibonacci

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

Factorial

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

Lottery

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

Greatest Common Divisor

publicstaticintgcd(inta,intb) {if (b ==0)returna;returngcd(b,a %b);    }

Prime

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

Media

Capture screen

publicstaticvoidcaptureScreen(Stringfilename)throwsAWTException,IOException {varscreenSize =Toolkit.getDefaultToolkit().getScreenSize();varscreenRectangle =newRectangle(screenSize);varrobot =newRobot();varimage =robot.createScreenCapture(screenRectangle);ImageIO.write(image,"png",newFile(filename));  }

Networking

HTTP GET

publicstaticHttpResponse<String>httpGet(Stringuri)throwsException {varclient =HttpClient.newHttpClient();varrequest =HttpRequest.newBuilder()            .uri(URI.create(uri))            .build();returnclient.send(request,BodyHandlers.ofString());  }

HTTP POST

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

String

Palindrome check

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

Reverse string

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

String to date

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

Anagram Check

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

Find Levenshtein distance

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

Class

Get methods name

publicstaticList<String>getAllMethods(finalClass<?>cls) {varlist =newArrayList<String>();for (varmethod :cls.getDeclaredMethods()) {list.add(method.getName());    }returnlist;  }

Get fields name

publicstaticList<String>getAllFieldNames(finalClass<?>cls) {returnArrays.stream(cls.getFields())            .map(Field::getName)            .collect(Collectors.toList());  }

Create object

publicstaticObjectcreateObject(Stringcls)throwsNoSuchMethodException,IllegalAccessException,InvocationTargetException,InstantiationException,ClassNotFoundException {varobjectClass =Class.forName(cls);varobjectConstructor =objectClass.getConstructor();returnobjectConstructor.newInstance();  }

I/O

Read file by stream

publicstaticList<String>readFile(StringfileName)throwsFileNotFoundException {try (Stream<String>stream =newBufferedReader(newFileReader(fileName)).lines()) {returnstream.collect(Collectors.toList());    }  }

InputStream to String

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

Thread

Create pool of threads

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

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Java100.0%

[8]ページ先頭

©2009-2025 Movatter.jp