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 17 compatible code snippets that you can understand in 30 seconds or less.

License

NotificationsYou must be signed in to change notification settings

webwebweb5/30-seconds-of-java

 
 

Repository files navigation

Inspired by30 seconds of code, this is a collection of reusable tested copy-pasteable Java 17 compatible code snippets that you can understand in 30 seconds or less. If you're interested in contributing to this library, please see theinstructions.

Algorithm

Mergesort

publicstaticvoidmergeSort(intarr[],intlow,inthigh){if(low>=high){return;    }intmid = (low+high)/2;mergeSort(arr,low,mid);mergeSort(arr,mid+1,high);merge(arr,low,high,mid);}privatestaticvoidmerge(int[]arr,intlow,inthigh,intmid) {inttemp[] =newint[(high-low+1)];inti =low;intj =mid+1;intk =0;while(i<=mid &&j<=high){if(arr[i]<arr[j]){temp[k++] =arr[i];i++;        }else{temp[k++] =arr[j];j++;        }    }while(i<=mid){temp[k++] =arr[i];i++;    }while(j<=high){temp[k++] =arr[j];j++;    }for(intm=0,n=low;m<temp.length;m++,n++){arr[n] =temp[m];    }}

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

InsertionSort

publicstaticvoidinsertionSort(int[]arr) {for (vari =1;i <arr.length;i++) {vartmp =arr[i];varj =i -1;while (j >=0 &&arr[j] >tmp) {arr[j +1] =arr[j];j--;      }arr[j +1] =tmp;    }  }

CountingSort

publicstaticvoidcountingSort(int[]arr) {varmax =Arrays.stream(arr).max().getAsInt();varcount =newint[max +1];for (varnum :arr) {count[num]++;    }for (vari =1;i <=max;i++) {count[i] +=count[i -1];    }varsorted =newint[arr.length];for (vari =arr.length -1;i >=0;i--) {varcur =arr[i];sorted[count[cur] -1] =cur;count[cur]--;    }varindex =0;for (varnum :sorted) {arr[index++] =num;    }  }

CycleSort

publicstaticint[]cycleSort(int[]arr) {intn =arr.length;inti =0;while (i <n) {intcorrectpos =arr[i] -1;if (arr[i] <n &&arr[i] !=arr[correctpos]) {inttemp =arr[i];arr[i] =arr[correctpos];arr[correctpos] =temp;      }else {i++;      }    }returnarr;  }

LinearSearch

publicstaticintlinearSearch(int[]arr,intitem) {for (inti =0;i <arr.length;i++) {if (item ==arr[i]) {returni;         }    }return -1; }

BinarySearch

publicstaticintbinarySearch(int[]arr,intleft,intright,intitem) {// Array arr[] must be sortedif (right >=left) {intmid =left + (right -left) /2;if (arr[mid] ==item) {returnmid;      }if (arr[mid] >item) {returnbinarySearch(arr,left,mid -1,item);      }returnbinarySearch(arr,mid +1,right,item);    }return -1;  }

SieveOfEratosthenes

publicstaticboolean[]sieveOfEratosthenes(intn) {boolean[]isPrime =newboolean[n +1];for (inti =0;i <isPrime.length;i++) {isPrime[i] =true;    }for (inti =2;i *i <=n;i++) {if (isPrime[i] ==true) {for (intj =i *i;j <=n;j +=i) {isPrime[j] =false;        }      }    }returnisPrime;  }

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 mean of integer array

publicstaticdoublearrayMean(int[]arr) {return (double)Arrays.stream(arr).sum() /arr.length;  }

Find median of integer array

publicstaticdoublearrayMedian(int[]arr) {Arrays.sort(arr);varmid =arr.length /2;returnarr.length %2 !=0 ? (double)arr[mid] : (double) (arr[mid] +arr[mid -1]) /2;  }

Find sum of integer array

publicstaticintarraySum(int[]arr) {returnArrays.stream(arr).sum();  }

Find maximum integer from the array

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

Find minimum integer from the array

publicstaticintfindMin(int[]arr) {returnArrays.stream(arr).reduce(Integer.MAX_VALUE,Integer::min);  }

Reverse array

publicstatic <T>T[]reverseArray(T[]array,intstart,intend) {if (start >end ||array ==null) {thrownewIllegalArgumentException("Invalid argument!");    }intminimumSizeArrayForReversal =2;if (start ==end ||array.length <minimumSizeArrayForReversal) {returnarray;    }while (start <end) {Ttemp =array[start];array[start] =array[end];array[end] =temp;start++;end--;    }returnarray;  }

Encoding

Base64 encode string

publicstaticStringencodeBase64(Stringinput) {returnBase64.getEncoder().encodeToString(input.getBytes());  }

Base64 decode string

publicstaticStringdecodeBase64(Stringinput) {returnnewString(Base64.getDecoder().decode(input.getBytes()));  }

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

Zip a directory

publicstaticvoidzipDirectory (StringsrcDirectoryName,StringzipFileName)throwsIOException {varsrcDirectory =newFile(srcDirectoryName);try (varfileOut =newFileOutputStream(zipFileName);varzipOut =newZipOutputStream(fileOut)    ) {zipFile(srcDirectory,srcDirectory.getName(),zipOut);    }  }publicstaticvoidzipFile(FilefileToZip,StringfileName,ZipOutputStreamzipOut)throwsIOException {if (fileToZip.isHidden()) {// Ignore hidden files as standardreturn;    }if (fileToZip.isDirectory()) {if (fileName.endsWith("/")) {zipOut.putNextEntry(newZipEntry(fileName));// To be zipped nextzipOut.closeEntry();      }else {// Add the "/" mark explicitly to preserve structure while unzipping action is performedzipOut.putNextEntry(newZipEntry(fileName +"/"));zipOut.closeEntry();      }varchildren =fileToZip.listFiles();for (varchildFile :children) {// Recursively apply function to all childrenzipFile(childFile,fileName +"/" +childFile.getName(),zipOut);      }return;    }try (varfis =newFileInputStream(fileToZip)// Start zipping once we know it is a file    ) {varzipEntry =newZipEntry(fileName);zipOut.putNextEntry(zipEntry);varbytes =newbyte[1024];varlength =0;while ((length =fis.read(bytes)) >=0) {zipOut.write(bytes,0,length);      }    }  }

Math

Fibonacci

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

Iterative Fibonacci

publicstaticintiterativeFibonacci(intnumber) {List<Integer>list =newArrayList<>();list.add(0);list.add(1);for (inti =2;i <number +1;i++) {list.add(list.get(i -2) +list.get(i -1));    }returnlist.get(number);  }

Factorial

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

Recursive Factorial

publicstaticintrecursiveFactorial(intnumber) {varinitial =0;if (number ==initial) {returninitial +1;    }returnnumber *recursiveFactorial(number -1);  }

Haversine formula

// Radius of sphere on which the points are, in this case Earth.privatestaticfinaldoubleSPHERE_RADIUS_IN_KM =6372.8;publicstaticdoublefindHaversineDistance(doublelatA,doublelongA,doublelatB,doublelongB) {if (!isValidLatitude(latA)        || !isValidLatitude(latB)        || !isValidLongitude(longA)        || !isValidLongitude(longB)) {thrownewIllegalArgumentException();    }// Calculate the latitude and longitude differencesvarlatitudeDiff =Math.toRadians(latB -latA);varlongitudeDiff =Math.toRadians(longB -longA);varlatitudeA =Math.toRadians(latA);varlatitudeB =Math.toRadians(latB);// Calculating the distance as per haversine formulavara =Math.pow(Math.sin(latitudeDiff /2),2)            +Math.pow(Math.sin(longitudeDiff /2),2) *Math.cos(latitudeA) *Math.cos(latitudeB);varc =2 *Math.asin(Math.sqrt(a));returnSPHERE_RADIUS_IN_KM *c;  }// Check for valid latitude valueprivatestaticbooleanisValidLatitude(doublelatitude) {returnlatitude >= -90 &&latitude <=90;  }// Check for valid longitude valueprivatestaticbooleanisValidLongitude(doublelongitude) {returnlongitude >= -180 &&longitude <=180;  }

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

Luhn algorithm

publicstaticintcalculateLuhnChecksum(longnum) {if (num <0) {thrownewIllegalArgumentException("Non-negative numbers only.");    }finalvarnumStr =String.valueOf(num);varsum =0;varisOddPosition =true;// We loop on digits in numStr from right to left.for (vari =numStr.length() -1;i >=0;i--) {finalvardigit =Integer.parseInt(Character.toString(numStr.charAt(i)));finalvarsubstituteDigit = (isOddPosition ?2 :1) *digit;finalvartensPlaceDigit =substituteDigit /10;finalvaronesPlaceDigit =substituteDigit %10;sum +=tensPlaceDigit +onesPlaceDigit;isOddPosition = !isOddPosition;    }finalvarchecksumDigit = (10 - (sum %10)) %10;// Outermost modulus handles edge case `num = 0`.returnchecksumDigit;  }

Greatest Common Divisor

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

Least Common Multiple

publicstaticintlcm(inta,intb) {intmax =a >b ?a :b;intmin =a <b ?a :b;for (inti =1;i <=min;i +=1) {intprod =max *i;if (prod %min ==0) {returnprod;      }    }returnmax *min;  }

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

Natural Number Binary Conversion

publicstaticStringtoBinary(longnaturalNumber) {if (naturalNumber <0) {thrownewNumberFormatException("Negative Integer, this snippet only accepts "              +"positive integers");    }if (naturalNumber ==0) {return"0";    }finalStack<Long>binaryBits =Stream.iterate(naturalNumber,n ->n >0,n ->n /2).map(n ->n %2)                    .collect(Stack::new,Stack::push,Stack::addAll);returnStream.generate(binaryBits::pop)            .limit(binaryBits.size()).map(String::valueOf).collect(Collectors.joining());  }publicstaticLongfromBinary(Stringbinary) {binary.chars().filter(c ->c !='0' &&c !='1').findFirst().ifPresent(in -> {thrownewNumberFormatException("Binary string contains values other than '0' and '1'");    });returnIntStream.range(0,binary.length())            .filter(in ->binary.charAt(binary.length() -1 -in) =='1')            .mapToLong(in -> ((long) 0b1) <<in).sum();  }

Elo Ratng

finalstaticintBASE =400;finalstaticintRATING_ADJUSTMENT_FACTOR =32;publicstaticdoublecalculateMatchRating(doublefirstPlayerRating,doublesecondPlayerRating,doubleresult) {doubleratingDiff = ((secondPlayerRating -firstPlayerRating) *1.0) /BASE;doublelogisticDiff =Math.pow(10,ratingDiff);doublefirstPlayerExpectedScore =1.0 / (1 +logisticDiff);doublefirstPlayerActualScore =result;doublenewRating =firstPlayerRating +RATING_ADJUSTMENT_FACTOR * (firstPlayerActualScore -firstPlayerExpectedScore);returnnewRating;  }

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) {for (inti =0,j =s.length() -1;i <j;i++,j--) {while (i <j && !Character.isLetter(s.charAt(i))) {i++;      }while (i <j && !Character.isLetter(s.charAt(j))) {j--;      }if (Character.toLowerCase(s.charAt(i)) !=Character.toLowerCase(s.charAt(j))) {returnfalse;      }    }returntrue;  }

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

Compare Version

publicstaticintcompareVersion(Stringv1,Stringv2) {Function<String,String[]>getVersionComponents =version ->version.replaceAll(".*?((?<!\\w)\\d+([.-]\\d+)*).*","$1","$1").split("\\.");varcomponents1 =getVersionComponents.apply(v1);varcomponents2 =getVersionComponents.apply(v2);intlength =Math.max(components1.length,components2.length);for (inti =0;i <length;i++) {Integerc1 =i <components1.length ?Integer.parseInt(components1[i]) :0;Integerc2 =i <components2.length ?Integer.parseInt(components2[i]) :0;intresult =c1.compareTo(c2);if (result !=0) {returnresult;      }    }return0;  }

Get common letters

publicstaticStringgetCommonLetters(StringfirstStr,StringsecondStr) {Set<String>commonLetters =newHashSet<>();for (CharactercurrentCharacter :firstStr.toCharArray()) {if (isCommonLetter(secondStr,currentCharacter)) {commonLetters.add(currentCharacter.toString());     }    }returnString.join(" ",commonLetters);  }privatestaticbooleanisCommonLetter(Stringstr,Charactercharacter) {returnstr.contains(character.toString()) &&Character.isLetter(character);  }

Maximum count of one character

publicstaticintgetMaxCharacterCount(Stringstr,charcharacter) {intcharacterCount =0;intmaxCharacterCount =0;for (inti =0;i <str.length();i++) {if ((str.charAt(i)) ==character) {characterCount++;maxCharacterCount =Math.max(maxCharacterCount,characterCount);     }else {characterCount =0;     }    }returnmaxCharacterCount; }

Remove Duplicate Characters from a string

publicstaticStringremoveDuplicateCharacters(Stringstr) {char[]charsOfStr =str.toCharArray();Set<String>uniqueCharacters =newHashSet<>();for (charcharacter :charsOfStr) {uniqueCharacters.add(String.valueOf(character));    }returnString.join("",uniqueCharacters);  }

Class

Get methods name

publicstaticList<String>getAllMethods(finalClass<?>cls) {returnArrays.stream(cls.getDeclaredMethods())            .map(Method::getName)            .collect(Collectors.toList());  }

Get public field names

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

Get all field names

publicstaticList<String>getAllFieldNames(finalClass<?>cls) {varfields =newArrayList<String>();varcurrentCls =cls;while (currentCls !=null) {fields.addAll(Arrays.stream(currentCls.getDeclaredFields())                .filter(field -> !field.isSynthetic())                .map(Field::getName)                .collect(Collectors.toList()));currentCls =currentCls.getSuperclass();      }returnfields;    }

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

Date

Add no of days to date

publicstaticDateaddDaysToDate(Datedate,intnoOfDays){if(date!=null){Calendarcal =Calendar.getInstance();cal.setTime(date);cal.add(Calendar.DAY_OF_MONTH,noOfDays);returncal.getTime();    }returnnull;   }

Add no of days to local date

publicstaticLocalDateaddDaysToLocalDate(LocalDatedate,longnoOfDays){returndate!=null ?date.plusDays(noOfDays) :null; }

Calculating the date difference between two dates

publicstaticlonggetYearsDifference(LocalDatefirstTime,LocalDatesecondTime) {varyearsDifference =ChronoUnit.YEARS.between(firstTime,secondTime);returnMath.abs(yearsDifference); }
publicstaticlonggetMonthsDifference(LocalDatefirstTime,LocalDatesecondTime) {varmonthsDifference =ChronoUnit.MONTHS.between(firstTime,secondTime);returnMath.abs(monthsDifference); }
publicstaticlonggetDaysDifference(LocalDatefirstTime,LocalDatesecondTime) {vardaysDifference =ChronoUnit.DAYS.between(firstTime,secondTime);returnMath.abs(daysDifference); }

About

Collection of reusable tested Java 17 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