Java One-liners
I am sharing some most commonly used one liner code blocks in Java
Collections
- Creating an array in single line
List<String> colors = Arrays.asList("Red", "Green", "Blue");
Files
- Copy file from one location to another location
Files.copy(Paths.get("/from/location/foo.txt"), Paths.get("/to/location/foo.txt"));
- Read file's content into String
String fileContent = new String(Files.readAllBytes(Paths.get("/path/to/file.txt")));
Source: https://onecompiler.com/questions/3spjxg3vt/how-to-read-a-file-content-into-string-in-java
- Filter all files with a particular extension
Arrays.asList(Paths.get("/path/to/folder").toFile().listFiles(file -> !file.isHidden() && file.isFile() && (file.getName().endsWith(".json")))).forEach(file -> {
// deal with the file
});
Source: https://onecompiler.com/questions/3spvtm8bq/filter-all-files-with-a-particular-extension-in-java
Dates
- Converting Date String into Date Object
Date dateObject = new SimpleDateFormat("yyyy-MM-dd").parse("2017-10-15");
Source: https://onecompiler.com/questions/3stfhdb4a/how-to-convert-string-into-date-in-one-line-in-java