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 code snippets

License

NotificationsYou must be signed in to change notification settings

java-code-help/java-snippets

 
 

Repository files navigation

Build status

Inspired by30 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

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 (inti =3;i *i <=number;i +=2) {if (number %i ==0) {returnfalse;}}returntrue;}

⬆ 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%

[8]ページ先頭

©2009-2025 Movatter.jp