Spring Boot

Spring Boot is an open-source framework to create Applications with minimum configurations. Spring boot provides a range of non-functional features that are common to applications like embedded servers, health checks, externalized configuration, CLI, etc. With Spring Boot, we can focus more on actual application logic and less on infrastructure. Some of the important features and concepts related to Spring Boot are listed below, which helps in getting started with Spring Boot.

Entry Point of Application

The entry point for any Spring Application is a class decorated with @SpringBootApplication annotation. This class contains the main method which will be invoked when the application boots.

Component Scan

Spring Boot uses a lot of annotation to increase developer productivity. For Applications to discover and initialize other components, Spring Boot uses @ComponentScan annotation. We can specify other Classes or packages that need to be scanned and initialized.

Configuration

Spring boot supports deferent ways of reading application configurations. We can provide configurations in YAML files or properties files or Java POJO Classes.

Profiles

Spring Boot supports Spring Profiles, which is a kind of different set of configuration values for different environments. For instance, we can have different database credentials for Production vs Test environments. Here we can put the database credentials values different under different Profiles.

Build Tools

Spring Boot supports different Build environments and technologies. For instance, we can use a maven to configure the build infrastructure, or we can also use Gradle, etc.

Spring Boot Starters

Spring boot can be used to develop a range of applications along with using different third party libraries. Spring boot starters provide pre-bundled dependencies for a particular type of application. In the Spring Boot Framework, all the starters follow a similar naming pattern: spring-boot-starter-*, where * denotes a particular type of application. For example if we want to develop an application based on Elastic Search we can use the starter spring-boot-starter-data-elasticsearch to bootstrap the application.

Java Sorting with List and Array

Array and List are some of the basic and very useful data structures. We often need to sort the data stored in Array and List. In this article, we examine some of the most common ways of sorting. Java provides Collections.sort class to sort Collections like List, Set, etc. Similarly, java also provides Arrays.sort() to sort Arrays. Both Collections.sort() and Arrays.sort() also takes Comparable instance which can be used to sort the data.

List Sorting

The following example shows different ways of sorting the Java List. We will be using Collections.sort() to sort the list. Collections class is part of the java.util package, and the sort method accepts a Comparator also. If we pass Comparator then the Comparator will be used to sort the objects in the collection. If Comparator is not passed then the natural ordering of the objects will be used to sort. Comparator.sort() takes a list of any objects provided that object implements a Comparable interface.
Create List and Add Data
Following code creates a list and adds data to it.
List nameList = new ArrayList();
nameList.add("Brazil");
nameList.add("Canada");
nameList.add("Japan");
nameList.add("China");
nameList.add("Australia");
nameList.add("Russia");
nameList.add("Nepal");
nameList.add("Italy");
nameList.add("Germany");
Collections.sort
The following code will sort the list using the natural ordering of the items in the list. For the above array, it will print Australia, Brazil, Canada, China, Germany, Italy, Japan, Nepal, Russia,
printMessage("Sort List ......");
Collections.sort(nameList);
nameList.forEach(a -> nicePrint(a));
Collection.sort with reverseOrder()
Like above now we are sorting using Collections.sort, but also passing reverseOrder() comparator. It will print Russia, Nepal, Japan, Italy, Germany, China, Canada, Brazil, Australia,
printMessage("Sort List Reverse Order .......");
Collections.sort(nameList, Collections.reverseOrder());
nameList.forEach(a -> nicePrint(a));
Collection.sort using a custom Comparator
Following code, sorts using Collections.sort and passed custom Comparator implemented using Lambda. It will print Australia, Brazil, Canada, China, Germany, Italy, Japan, Nepal, Russia,
printMessage("Sort List using custom Comparator");
Collections.sort(nameList, (k1, k2) -> (k1.compareTo(k2)));
nameList.forEach(a -> nicePrint(a));
Sort Part of the List
We can also sort part of the list. For that, we can pass subList() of the actual list to the Collections.sort() method. The following code will print Brazil, Canada, Japan, China, Australia, Russia, Nepal, Italy, Germany. See the first 3 country names are sorted.
Collections.sort(nameList.subList(0, 3));
nameList.forEach(a -> nicePrint(a));

Array Sorting

The following example shows different ways of sorting the Java Array. We will be using Arrays.sort() to sort the array.
Sort Array
Sort the data array using Arrays.sort(). It will print the following It will print Australia, Brazil, Canada, China, Germany, Italy, Japan, Nepal, Russia.
Arrays.sort(data);
Sort Array in reverse order
Sort in reverse order, bypassing reverseOrder() to the Arrays.sort() method. It will print Russia, Nepal, Japan, Italy, Germany, China, Canada, Brazil, Australia,
Arrays.sort(data, Collections.reverseOrder());
Sort Array by using a custom comparator
Following code sorts data using Arrays.sort and a custom Comparator by using lambda.
Arrays.sort(data, (k1, k2) -> (k1.compareTo(k2)));
Sorting part of Array
We can sort part of an array also, the following example shows how to sort only the first 3 items in the Array.
Arrays.sort(data, 0, 3);
Sorting Array using parallel sort.
We can also sort the data by using parallelSort().
Arrays.parallelSort(data);
Summary
  • Collections.sort() can be used to sort a list of objects.
  • Collections.sort() uses BinarySearch algorithm.
  • Arrays.sort() uses Mergesort or Timsort algorithms to sort the data.
  • Collections.sort() and Arrays.sort() throws NullPointerException if data is null.
  • The object that we are sorting should implement java.langComparable interface.

Stack data structure

Stack is a LIFO data structure used to store a collection of objects. Individual items can be added and stored in a stack using a push operation. Objects can be retrieved using a pop operation, which removes an item from the top of the stack. Since it is LIFO(Last in First Out) Item added last is the first to come out of the stack. Java comes with multiple options when choosing a Stack. The first one is the old java.util.Stack and the second one is interface Deque and its implementations like ArrayDeque, Linkedlist etc.
Common operations on stack data structure are as follows,
  • push : Add data to top of the stack.
  • peek : Look what is on the top of the stack without removing it.
  • pop: Remove the object at the top of this stack.
  • size.: Size of the stack, which is number of items on the stack.

Different options for Stack

Java provides mainly 
java.util.Stack and java.util. Deque Implementation classes (ArrayDeque, Linkedlist) as stack data structures . Choosing the implementation of choice depends on the use case we are dealing with. Following sections shows using java.util.Stack and java.util.ArrayDeque as Stack data structure.

java.util.Stack as stack data structure

java.util.Stack class extends java.util.Vector and represents a LIFO data structure. It is one of the oldest class that ships with Java 1 onwards. 
Following example show how to initialize a Stack() object, some common operations on stack, like push items to the stack, check size of the stack, peek the top of the stack and iterate over the stack etc.
Stack stack = new Stack();

//push items to stack
stack.push("Transformers (2007)");
stack.push("Transformers: Revenge of the Fallen (2009)");
stack.push("Transformers: Dark of the Moon (2011)");
stack.push("Transformers: Age of Extinction (2014)"); 
stack.push("Transformers: The Last Knight (2017)"); 
stack.push("Bumblebee (2018)"); 

//Size of the stack
System.out.println("Size of the stack = " + stack.size());

//Peek the top of the stack
System.out.println("Peek top of the stack = " + stack.peek());
//Pop the top of the stack
System.out.println("Peek top of the stack = " + stack.pop()); 

//Print entries of the Stack
System.out.println("Entries in the Stack");
stack.forEach(a-> System.out.println(a));

//Print entries of the Stack Using Iterator
System.out.println("Entries in the Stack Using Iterator");
Iterator it = stack.iterator();
while(it.hasNext()) {
  String item = it.next();
  System.out.println(item);
}
java.util.Deque as Stack data structure
java.util.Deque is also known as double ended queue is an interface that extends java.util.Queue.
The Deque interface adds some interesting methods like pop() addFirst(), addLast() etc, which allows us to add and remove the data from both end of the queue,  deque implementations can be used both as a Stack (LIFO) or Queue (FIFO) data structure. 

Following diagram shows the Object hierarchy for Deque.


Java provides two implementation of java.util.Deque, ArrayDeque and LinkedList.
Following example shows how to use Deque as Stack. Here we are using ArrayDeque as an Deque instance. And we are doing exactly the same things that we did with Stack in the above example.
Deque stack2 = new ArrayDeque();

//push items to stack
stack2.push("Transformers (2007)");
stack2.push("Transformers: Revenge of the Fallen (2009)");
stack2.push("Transformers: Dark of the Moon (2011)");
stack2.push("Transformers: Age of Extinction (2014)"); 
stack2.push("Transformers: The Last Knight (2017)"); 
stack2.addFirst("Bumblebee (2018)");  // same as push()

//Size of the stack
System.out.println("Size of the stack = " + stack2.size());

//Peek the top of the stack
//Prints Bumblebee (2018)
System.out.println("Peek top of the stack = " + stack2.peekFirst()); 

//Pop the top of the stack
//Prints Bumblebee (2018)
System.out.println("Peek top of the stack = " + stack2.pop()); 
//Print entries of the Stack System.out.println("Entries in the Stack"); stack2.forEach(a-> System.out.println(a)); //Print entries of the Stack Using Iterator System.out.println("Entries in the Stack Using Iterator"); Iterator it2 = stack2.iterator(); while(it2.hasNext()) { String item = it2.next(); System.out.println(item); }
Summary
  • java.util.Stack is synchronized data structure.
  • java.util.Stack extends Vector internally.
  • Deque is an interface, and it has multiple implementations like ArrayDeque, LinkedList etc.
  • Deque is newer compared to java.util.Stack is more preferable as a Stack implementation.
  • Deque can be used both as a Stack or Queue data structure, depending on which methods we are using to add or remove item from the Deque. 

References


QUEUE IN JAVA

Queue is FIFO(First in First Out) data structure, which means that element inserted first will be removed first. In Java Queue is an interface and it provides multiple implementation of Queue with different properties, which makes certain implementation better suited for certain scenarios. Queue interface extends the Collection Interface so it provides common collection methods like size(), isEmpty(), addAll(), clear() etc. This article covers some of the common examples of using Queue in java
Most generally when we need a FIFO data structure we can use PriorityQueue, LinkedList, ArrayDeque classes. They can be classified as Queue and Deque.

Queue

The interface java.util.Queue is the Queue interface. PriorityQueue, LinkedList are the most common Queue implementations. When we need Queue we can use instance of any of the PriorityQueue, LinkedList classes.
Queue Implementations
  • PriorityQueue
  • LinkedList
PriorityQueue Example
Create instance of PriorityQueue, add 5 items to it. Print the size, and peek the first item.
Queue q1 = new PriorityQueue();

//Add 5 items to q1
q1.offer("a");
q1.offer("b");
q1.offer("c");
q1.offer("d");
q1.offer("e");

System.out.println("Size of q1 = " + q1.size());
System.out.println("First Element of q1 = " + q1.peek());
Queue Iteration
Iterate over a Queue and print its item.
//iterate
System.out.println("Iterating on Queue");
Iterator it1 = q1.iterator();

while (it1.hasNext()) {
  String item = it1.next();
  System.out.print(item + " ");
}

Deque

java.util.Deque is the Deque interface. Deque is also known as double ended Queue. That means we can add and remove items at both ends of the queue. LinkedList and ArrayDeque implements DeQueue Interface(Double ended queue).
Deque Implementations
  • LinkedList
  • ArrayDeque
Deque Example
Create two queue q2 and q3. Since we are creating instances of Deque, we can access both end of the contents. Like peekFirst(), peekLast() to peek the first and last element respectively.
Deque q2 = new LinkedList();
Deque q3 = new ArrayDeque();
System.out.println("First Element of q2 = " + q2.peekFirst());
System.out.println("Last  Element of q2 = " + q2.peekLast());

Concurrent Queue Implementations

The java.util.concurrent package contains BlockingQueue and its implemented classes. BlockingQueue is used in multi threaded application, when we want a thread to wait or blocked unless we have item in the thread.
BlockingQueue implemented classes.
  • LinkedBlockingQueue — an optionally bounded FIFO blocking queue backed by linked nodes
  • ArrayBlockingQueue — a bounded FIFO blocking queue backed by an array
  • PriorityBlockingQueue — an unbounded blocking priority queue backed by a heap
  • DelayQueue — a time-based scheduling queue backed by a heap
  • SynchronousQueue — a simple rendezvous mechanism that uses the BlockingQueue interface
Summary
  • PriorityQueue, LinkedList, ArrayDeque are suitable in most cases.
  • Deque can be used as a stack also.
  • LinkedList and ArrayDeque are most commonly Deque implementations.
  • PriorityQueue is most commonly used Queue implementation

How to Sort HashMap in java

This article covers some of the aspects of sorting Map in Java. Java Map comes in different flavours, like HashMap, TreeMap, LinkedHashMap etc. TreeMap for instance will sort the data based on the keys. We can also pass a custom Comparator to sort based on the keys as per the custom sort algorithm.
We can have two requirements in terms of sorting, first one is sorting by Keys and second is Sorting by Values. Following examples demonstrates few approaches for sorting by key and sorting by value. Following examples uses Java Lambda and Stream api to sort Java HashMap instance.

Sort by Value

Map sort by value in revere order
Following code snippet sorts the map based on value in reverse order and populates a new map reverseSortedMap from the data.
//LinkedHashMap preserve the ordering of elements in which they are inserted
Map reverseSortedMap =  new LinkedHashMap();
//Use Comparator.reverseOrder() for reverse ordering
map.entrySet()
    .stream()
    .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) 
    .forEachOrdered(x -> reverseSortedMap.put(x.getKey(), x.getValue()));

Sort By Key

Map sort by key in revere order
Following code snippet sorts the map based on the keys in reverse order.
//LinkedHashMap preserve the ordering of elements in which they are inserted
Map reverseSortedMapByKey =  new LinkedHashMap();;
//Use Comparator.reverseOrder() for reverse ordering
map.entrySet()
    .stream()
    .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())) 
    .forEachOrdered(x -> reverseSortedMapByKey.put(x.getKey(), x.getValue()));
 

System.out.println("Sorted by Value Map : " + reverseSortedMapByKey);

Full Example

MapSortJava
public class MapSortJava {

  public static void main(String[] args) {

    Map<Integer, String> map = new HashMap<Integer, String>();
    map.put(101, "Tokyo");
    map.put(3, "New York");
    map.put(2, "San Francisco");
    map.put(14, "Los Angels");
    map.put(5, "Austin");

    System.out.println("Unsorted Map : " + map);
    
   // LinkedHashMap preserve the ordering of elements in which they are inserted
    Map<Integer, String> reverseSortedMap = new LinkedHashMap<Integer, String>();;
    // Use Comparator.reverseOrder() for reverse ordering
    map.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
        .forEachOrdered(x -> reverseSortedMap.put(x.getKey(), x.getValue()));
    System.out.println("Sorted by Value Map : " + reverseSortedMap);


    // LinkedHashMap preserve the ordering of elements in which they are inserted
    Map<Integer, String> reverseSortedMapByKey = new LinkedHashMap<Integer, String>();;
    // Use Comparator.reverseOrder() for reverse ordering
    map.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
        .forEachOrdered(x -> reverseSortedMapByKey.put(x.getKey(), x.getValue()));
    System.out.println("Sorted by Value Map : " + reverseSortedMapByKey);

  }
}
Output
Unsorted Map : 2 ==> San Francisco 3 ==> New York 101 ==> Tokyo 5 ==> Austin 14 ==> Los Angels Sorted by Value Map (Reverse) : 2 ==> San Francisco 3 ==> New York 101 ==> Tokyo 5 ==> Austin 14 ==> Los Angels Sorted by Value Map (Reverse) : 101 ==> Tokyo 14 ==> Los Angels 5 ==> Austin 3 ==> New York 2 ==> San Francisco
Summary of steps
  • Get the entry set by calling the Map.entrySet().
  • Get the entry set stream by calling stream() method.
  • Use the Map.Entry.comparingByValue() or Map.Entry.comparingByKey().
  • Call the sorted method with a Comparator.
  • call the terminal operation forEachOrdered to store the each entries in the new Map.

How to use custom comparator for TreeMap

This article covers some of the aspects of sorting Map in Java. Java Map comes in different flavors, like HashMap, TreeMap, LinkedHashMap etc. TreeMap for instance will sort the data based on the keys. We can also pass a custom Comparator to sort based on the keys as per the custom sort algorithm.
TreeMap sorts based on natural ordering of the keys if no custom Comparator is provided. To use a custom Comparator we need to pass the Comparator in the TreeMap Constructor.

Simple TreeMap

TreeMap without any Comparator
Following code creates a TreeMap and adds some data to it. After that we print the TreeMap. As No comparator is specified, the data is sorted by natural ordering of the keys.
TreeMap map = new TreeMap();
    map.put(1, "A");
    map.put(3, "C");
    map.put(2, "B");
    map.put(4, "D");
    map.put(5, "E");


    System.out.println("\nPrint Map ");
    map.forEach((a, b) -> {
      printKeyVal(a,b);
    });;
Print Map Key: 1 Value: A Key: 2 Value: B Key: 3 Value: C Key: 4 Value: D Key: 5 Value: E

TreeMap with Comparator

TreeMap with reverse order Comparator
In this case we are passing a built in Comparator to sort the keys reversely. From the result we can see that the data is sorted in reverse order of the keys.
System.out.println("\nPrint Map with Reverse Comparator");
TreeMap map2 = new TreeMap(Collections.reverseOrder());
    map2.putAll(map);
    map2.forEach((a, b) -> {
      printKeyVal(a, b);
 });
Print Map with Reverse Comparator Key: 5 Value: E Key: 4 Value: D Key: 3 Value: C Key: 2 Value: B Key: 1 Value: A

Custom Comparator

Following examples shows implementation of two custom Comparator, one with inner class second one with java 8 Lambda. Both the Comparator works exactly same, that is it sorts the data in reverse order.
With Inner Classes
Custom Comparator with Inner Class to sort the keys in reverse order.
Comparator orderByKeyDesc = new Comparator() {
@Override
 public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
      }
};
Lambda Comparator.
Java 8 Lambda to implement Comparator
Comparator orderByKeyDesc2 = (Integer o1, Integer o2) -> o2.compareTo(o1);

Full Example

TreeMapCustomComparator
Full example with Custom Comparator that is passed to the TreeMap.
public class TreeMapCustomComparator {

  public static void main(String[] args) {

    TreeMap map = new TreeMap();
    map.put(1, "A");
    map.put(3, "C");
    map.put(2, "B");
    map.put(4, "D");
    map.put(5, "E");


    System.out.println("\nPrint Map ");
    map.forEach((a, b) -> {
      printKeyVal(a, b);
    });;

   
    System.out.println("\nPrint Map with Reverse Comparator");
    TreeMap map2 = new TreeMap(Collections.reverseOrder());
    map2.putAll(map);
    map2.forEach((a, b) -> {
      printKeyVal(a, b);
    });


    //Custom Comparator with Inner Class
    Comparator orderByKeyDesc = new Comparator() {
      @Override
      public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
      }
    };

    //Custom Comparator with Lambda
    Comparator orderByKeyDesc2 = (Integer o1, Integer o2) -> o2.compareTo(o1);

    System.out.println("\nPrint Map with Custom Reverse Comparator Java Lambda");
    TreeMap map3 = new TreeMap(orderByKeyDesc2);
    map3.putAll(map);

    map3.forEach((a, b) -> {
      printKeyVal(a, b);
    });

  }

  /* Utility method to print key value pairs nicely */
  private static void printKeyVal(Object a, Object b) {
    System.out.print("Key: " + a + "  Value: " + b + "     ");
  }


}
Print Map Key: 1 Value: A Key: 2 Value: B Key: 3 Value: C Key: 4 Value: D Key: 5 Value: E Print Map with Reverse Comparator Key: 5 Value: E Key: 4 Value: D Key: 3 Value: C Key: 2 Value: B Key: 1 Value: A Print Map with Custom Reverse Comparator Java Lambda Key: 5 Value: E Key: 4 Value: D Key: 3 Value: C Key: 2 Value: B Key: 1 Value: A

Convert ByteBuffer to String and viceversa

ByteBuffer Class is part of Java NIO. It extends java.nio.Buffer and used to handle data read and write to NIO Channels. This article demonstrates few ways to handle conversion between ByteBuffer to String and converting String to ByteBuffer object.
Convert String to ByteBuffer
Following code converts the String data to ByteBuffer object using Charset.forName. We need to specify the appropriate character set .
String data = "this is my string";
ByteBuffer buff = Charset.forName("UTF-8").encode(data);
Convert ByteBuffer to String
Following code sample shows two methods, both can be used to convert ByteBuffer object back to a String. We need to specify the same character set, that was used to encode, otherwise we might get a different String.
public static String getData (ByteBuffer buff) {
    return new String(buff.array(), StandardCharsets.UTF_8 );
  }
  
public static String getData2 (ByteBuffer buff) {
    return StandardCharsets.UTF_8.decode(buff).toString();
}

Java File Channel

FileChannel is available as a part of Java NIO (New IO).Java NIO (New IO) is an alternative to the standard Java IO API's. Java NIO offers a different way of working with IO than the standard IO API's. File channels are safe for use by multiple concurrent threads. This article demonstrate with working example of how to write and read file using FileChannel.
Advantages of File Channels
  • File channels are safe for use by multiple concurrent threads.
  • Reading and writing at a specific position in a file.
  • transfer file data from one channel to another at a faster rate.
  • lock a section of a file to restrict access by other threads.

Example of Reading and Writing File

Following example demonstrate how to read and write file using FileChannel.
JavaFileChannelHelper
package bootng.com.files;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

public class JavaFileChannelHelper {
  
  public static void main(String[] args) {
    JavaFileChannelHelper example = new JavaFileChannelHelper();
    try {
      example.write("samplefile.txt","This is it");
      String content = example.read("samplefile.txt");
      System.out.println(content + "  " );
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  public String read(String source) throws IOException {
    StringBuilder content = new StringBuilder("");
    RandomAccessFile file = new RandomAccessFile(source, "r");
    FileChannel channel = file.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(48);
    while (channel.read(buf) > 0) {
      content.append(new String(buf.array(), StandardCharsets.UTF_8 ));
    }
     System.out.println("Read success!");
    return content.toString();
  }
  
  public void write(String source, String content) throws IOException {
    RandomAccessFile file = new RandomAccessFile(source, "rw");
    FileChannel channel = file.getChannel();
    ByteBuffer buff = ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8));
    channel.write(buff);
    System.out.println("Write success!");
      }
}
Notes
  • Channels read and write buffers containing the content.
  • Channels are bi directional, that is we can both write and read in a channel.

Photo by Viktor Talashuk on Unsplash

How to list all files in a directory in java

Say we want get names of all the files under a directory and sub directories. Basically we need to able to look under each sub directory and if it has any files add to the result. This sounds like a problem that can be solved recursively.
Get Files
List the file names by calling listFiles on the root path, and then recursively calling it if we get any directory.
public List getFiles (String path) {
     List result = new ArrayList();
     File root = new File (path);
     File[] filesNDirectories = root.listFiles();
     
     for (var file: filesNDirectories) {
       if (file.isFile()) {
         result.add(file.getName());
       } 
       else if (file.isDirectory()) {
         List subResult = getFiles(file.getPath());
         result.addAll(subResult);
       }
     }
     return result; 
  }
Files.walk
Files.walk returns a stream containing
public List getFiles(String path) throws IOException {
    Stream walk = Files.walk(Paths.get(path));
    List result = walk.filter(Files::isRegularFile).map(x -> x.getFileName().toString())
        .collect(Collectors.toList());

    result.forEach(System.out::println);
    walk.close();

    return result;
  }

Example


Java Files.walk examples

Java File.walk method is available in java 8. It is very useful to traverse the the content of a file tree. Walks goes in a depth first fashion and return a Stream object. We can then work with the stream to get the required result. Like we can filter only directories, find files matching some name etc. This article covers three example of using File.walk to list all the directories, files and both.
List all the folders
List all the directories inside the location specified by path.
public List getFolders(String path) throws IOException {
    Stream walk = Files.walk(Paths.get(path));
    List result = walk.filter(Files::isDirectory).map(x -> x.getFileName().toString())
        .collect(Collectors.toList());
    result.forEach(System.out::println);
    walk.close();
    return result;
  }
List all files
Similar to above method, but the filter condition is different. Here we are filtering only regular fiels with Files::isRegularFile.
public List getFiles(String path) throws IOException {
    Stream walk = Files.walk(Paths.get(path));
    List result = walk.filter(Files::isRegularFile).map(x -> x.getFileName().toString())
        .collect(Collectors.toList());

    result.forEach(System.out::println);
    walk.close();

    return result;
  }
Files and Directories
Following method will list all the directories: with files inside it. It is similar to linux command ls *.
public List getFoldersAndFiles(String path) throws IOException {
    Stream walk = Files.walk(Paths.get(path));
    List result = walk.map(x -> {
      if (Files.isDirectory(x)) {
        return x.getFileName().toString() + ":";
      } else
        return x.getFileName().toString();
    }).collect(Collectors.toList());

    result.forEach(System.out::println);
    walk.close();

    return result;
  }

References


Table of Content

Iterating Java Map

Java Map is an object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. If we want to get the object stored at a particular key we can do so using the the get method.
But if we want to traverse all the objects, then we have different ways of doing the same.

Different Options

In Java we have the following four options to iterate over java map.
Map Iterator
Classic way of using the Iterator of the keySet.
//Iterator
Map map = new TreeMap();
System.out.println("Print using Iterator");
Iterator it = map.keySet().iterator();

while (it.hasNext()) {
  Integer k = it.next();
  String  v = map.get(k);
  System.out.print( "Key=" + k + " Value=" + v + "  ");
}
Java 8 forEach
We can use the forEach introduced in Java 8 to iterate over key and value.
//forFeach
Map map = new TreeMap();
System.out.println("\nPrint using Java 8 forEach");
map.forEach((k,v) -> System.out.print("Key=" + k + " Value=" + v + "  "));
For loop over the keyset
Using for loop over the key set, and then getting the respective value from the map.
//For loop over the keySet
Map map = new TreeMap();
System.out.println("\nPrint using for loop");
for (Integer k : map.keySet()) {
  String  v = map.get(k);
  System.out.print("Key=" + k + " Value=" + v + "  ");
}

Full Example

Full Java Class with all the above options to iterate over map.
MapIterationExample
package bootng.com.learn.collections;

public class MapIterationExample {
  public static void main(String[] args) {
    Map<Integer, String> map = new TreeMap<Integer, String>();
    map.put(1, "A");
    map.put(3, "C");
    map.put(2, "B");
    map.put(4, "D");
    map.put(5, "E");

    // Iterator
    System.out.println("Print using Iterator");
    Iterator<Integer> it = map.keySet().iterator();

    while (it.hasNext()) {
      Integer k = it.next();
      String v = map.get(k);
      System.out.print("Key=" + k + " Value=" + v + "  ");
    }

    // forFeach
    System.out.println("\nPrint using Java 8 forEach");
    map.forEach((k, v) -> System.out.print("Key=" + k + " Value=" + v + "  "));

    // For loop over the keySet
    System.out.println("\nPrint using for loop");
    for (Integer k : map.keySet()) {
      String v = map.get(k);
      System.out.print("Key=" + k + " Value=" + v + "  ");
    }

    // Stream
    System.out.println("\nPrint using stream");
    map.keySet().stream().forEach(key -> {
      System.out.print("Key=" + key + " Value=" + map.get(key) + "  ");
    });    
  }
}
Output
Print using Iterator
Key=1 Value=A  Key=2 Value=B  Key=3 Value=C  Key=4 Value=D  Key=5 Value=E  
Print using Java 8 forEach
Key=1 Value=A  Key=2 Value=B  Key=3 Value=C  Key=4 Value=D  Key=5 Value=E  
Print using for loop
Key=1 Value=A  Key=2 Value=B  Key=3 Value=C  Key=4 Value=D  Key=5 Value=E  
Print using stream
Key=1 Value=A  Key=2 Value=B  Key=3 Value=C  Key=4 Value=D  Key=5 Value=E