logo image

Java One-liners



I am sharing some most commonly used one liner code blocks in Java

Collections

  1. Creating an array in single line
List<String> colors = Arrays.asList("Red", "Green", "Blue");

Source: https://onecompiler.com/questions/3spjqkd6g/how-to-create-an-arraylist-with-values-in-one-line-in-java

Files

  1. Copy file from one location to another location
Files.copy(Paths.get("/from/location/foo.txt"), Paths.get("/to/location/foo.txt"));

Source: https://onecompiler.com/questions/3spjtx6qz/how-to-copy-file-from-one-location-to-another-location-in-java

  1. 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

  1. 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

  1. 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