Java 8 Code Quickers

Listing All Files in a Directory

To list files in a different directory, we can replace . with the full path of the
directory that we desire.
 
Files.list(Paths.get(".")).forEach(System.out::println);

List Hidden Files

new File(".").listFiles(File::isHidden);

Filter files based on Extension

Files.newDirectoryStream(Paths.get("fpij"), path -> path.toString().endsWith(".txt"))
.forEach(System.out::println);


Using below Array list will be considered for all queries


List<String> fruits= Arrays.asList("Apple", "Mango", "Grapes", "Strawberry", "Banana","
Blackberry","Papaya","Peach","Cheery"); 

Iterating through a List

Eg1: fruits.forEach(fruit-> System.out.println(fruit));
Eg2: fruits.forEach(System.out::println); 

Transforming List to lowercase

Eg1:
final List<String> lowerCase = new ArrayList<String>();
friends.forEach(fruit-> lowerCase .add(fruit.toLowerCase()));
System.out.println(lowerCase); 

Eg2: Using Lamba Expressions
 fruits.stream()
.map(fruit-> fruit.toUpperCase())
.forEach(fruit-> System.out.print(fruit+ ","));
System.out.println();

Eg3:  Using Method References

fruits.stream()
.map(String::toUpperCase)
.forEach(
fruit-> System.out.println(fruit));

 Count length of each array value

fruits.stream()
.map(fruit-> fruit.length())
.forEach(counter -> System.out.print(counter + ","));







No comments:

Post a Comment

Different Types of Keyboard Inputs : Type, SendKeys & Device Replay

1. Most objects support the TYPE method.  Type will enter the specified string into an object or perform a certain keyboard combinat...