Java Threads Print Alternative Odd Even Numbers

This article shows how to print Even and Odd numbers alternatively using Java. It uses Two Java threads and a Class with two methods to print even numbers and odd numbers respectively.

What we are trying to achieve

We want to print even and odd numbers alternatively but using two threads. Essentially it is the interaction between two threads utilizing the wait() and notify() methods. One thread completes a task (printing a single even number) then it is put on wait state so that the other thread can get a chance to do its job (printing odd number) and this goes on until we are done with printing a set of numbers determined by max.
How it will work
  • Print Class (Print.java) with two synchronized methods even() and odd() which print even or odd numbers respectively.
  • Each method is synchronized so that two threads cannot execute them concurrently.
  • Each method first calls notifyAll() to so that other threads that are waiting can be wake up.
  • It then prints a number (even or odd) and then calls the wait() method on the current thread so it goes to waiting state.

Java Code

Print.java
This Class essentially has two synchronized methods. The constructor of this class takes a max number as a parameter. This max number is the limit to which the numbers will be printed. It has two synchronized methods to print even and odd numbers alternatively.
class Print {
  int max;

  public Print(int max) {
    this.max = max;
  }

  public synchronized void even() throws InterruptedException {
    for (int i = 0; i <= max; i++) {
      notifyAll();
      if (i % 2 == 0)
        System.out.println(Thread.currentThread().getName() + ":: " + i);
      wait();
    }
  }

  public synchronized void odd() throws InterruptedException {
    for (int i = 0; i <= max; i++) {
      notifyAll();
      if (i % 2 != 0)
        System.out.println(Thread.currentThread().getName() + ":: " + i);
      wait();
    }
  }
}
Threads.java
Here we are creating an instance of Print class and creating two Threads. From the first thread, we are calling print.even() method, from the second thread we are calling print.odd() method.
Print print = new Print(10);

//Thread to print even numbers
Thread t1 = new Thread(new Runnable() {
  @Override
  public void run() {
    try {
      print.even();
    } catch (InterruptedException e) {
    }
  }
});

//Thread to print odd numbers
Thread t2 = new Thread(new Runnable() {
  @Override
  public void run() {
    try {
      print.odd();
    } catch (InterruptedException e) {
    }
  }
});

t1.setName("Even Thread");
t2.setName(" Odd Thread");

t1.start();
t2.start();
Console Output
Even Thread:: 0
Odd Thread:: 1
Even Thread:: 2
Odd Thread:: 3
Even Thread:: 4
Odd Thread:: 5
Even Thread:: 6
Odd Thread:: 7
Even Thread:: 8
Odd Thread:: 9
Even Thread:: 10
Conclusion
  • From the odd() or even () method we have to first call notify or notifyAll() first.
  • Both odd() or even() method should be synchronized otherwise calling notifyAll() or wait() will throw exception

Java Thread States

A thread in Java at any point of time exists in any one of the 6 states. This article give a quick introduction of different Thread states and respective methods which results in threads state change.
Following are the states of a Java Thread
  • New: Thre thread is just created by using start() method on the tread
  • Runnable: Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual machine but it may be waiting for other resources from the operating system such as a processor.
  • Blocked: A thread in the blocked state is waiting for a monitor lock
  • Waiting: A thread is in the waiting state due to calling one of the following methods:
    Object.wait() with no timeout
    Thread.join() with no timeout
    LockSupport.park
  • Timed Waiting: A thread is in the timed waiting state due to calling one of the following methods with a specified positive waiting time:Thread.sleep (long)
    Object.wait (long)
    Thread.join (long)
    LockSupport.parkNanos
    LockSupport.parkUntil
  • Terminated: The thread has completed execution

Matrix Rotation in Java

In this article, we will explore a few different ways to rotate a matrix clock by 90 degrees.

Rotating Matrix to 90 Clockwise

Following is our Matrix. 

[    1        2        3    ]

[    4        5        6    ]

[    7        8        9    ]

We will explore multiple ways to rotate this matrix clockwise 90 

With Matrix Transpose

Matrix transpose is a flipped version of the matrix along its diagonal. In short, it is the same as interchanging the rows with columns. For the above matrix the transposed matrix will look like. 

[    1        4        7    ]

[    2        5        8    ]

[    3        6        9    ]

Also, the transposed matrix is equivalent to 90 Left rotation of the original array.
RoateMatrixWithTranspose
Here the Rotation of the matrix is done in two steps
1) We transpose the matrix 2) And we interchange the columns
public void rotateMatrixRight90Transpose(int[][] mat) {

    int m = mat.length;
    int n = mat[0].length;

    for (int i = 0; i < m; i++) {
      for (int j = i; j < n; j++) {
        int x = mat[i][j];
        mat[i][j] = mat[j][i];
        mat[j][i] = x;
        System.out.println("IC" + i + ":" + j);
      }
    }

    // swap cols
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n / 2; j++) {
        // swap mat[i][j] with mat[N-i-1][j]
        int temp = mat[i][j];
        mat[i][j] = mat[i][n - j - 1];
        mat[i][n - j - 1] = temp;
      }
    }
  }
Output

Matrix Rotation with Transpose

<= Original Matrix  =>

[    1        2        3    ]

[    4        5        6    ]

[    7        8        9    ]



<= After Transpose =>

[    1        4        7    ]

[    2        5        8    ]

[    3        6        9    ]



<= After Rotation =>

[    7        4        1    ]

[    8        5        2    ]

[    9        6        3    ]

Matrix Rotation in Single pass

MatrixRotation.java
The following code will rotate the matrix in a single pass.
public void rotate(int[][] matrix) {
    int n = matrix.length;
    for (int i = 0; i < (n + 1) / 2; i++) {
      for (int j = 0; j < n / 2; j++) {
        int temp = matrix[n - 1 - j][i];
        matrix[n - 1 - j][i] = matrix[n - 1 - i][n - j - 1];
        matrix[n - 1 - i][n - j - 1] = matrix[j][n - 1 - i];
        matrix[j][n - 1 - i] = matrix[i][j];
        matrix[i][j] = temp;
      }
    }
  }
Output

Matrix Rotation with single pass

<= Original Matrix  =>

[    1        2        3    ]

[    4        5        6    ]

[    7        8        9    ]



<= After Rotation =>

[    7        4        1    ]

[    8        5        2    ]

[    9        6        3    ]


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  

The char data type is a single 16-bit Unicode character. If we need to know the unicode value represented by the character we have several options. Following covers some of the options
To get Unicode of a character
If we want to know the unicode value for '1', we can use Integer.toString()
char myChar = '1';
String unicode = Integer.toString(myChar);
System.out.print(unicode); // Prints 49
To get Unicode of a character of a String
If we want to know the unicode value for "1", we can use Integer.toString()
String inputString = "1";
int unicodeFromString = inputString.codePointAt(0);
System.out.print(unicodeFromString); // Prints 49

Iterate over Java MAP

Map is an interface and is a part of the java collections framework. Java collections framework provides a number of Map implementations like HashMap, TreeMap, LinkedHashMap etc. This post contains different ways of traversing through a HashMap, which are given below:
Following section illustrates different ways to traverse the map data. Since map contains key-value data, most of them traverse through the keys and get the corresponding data.
Map initialization
Following code creates instance of a TreeMap and puts 5 key-value pairs to it.
Map map = new TreeMap();
map.put(1,"A");
map.put(3,"C");
map.put(2,"B");
map.put(4,"D");
map.put(5,"E");
Iterator
Traverse using Iterator of the key set.
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);
}
Forloop
Following code traverse the map by using a for loop on the key set.
//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
Following code traverse the map using a stream on the key set.
System.out.println("\nPrint using stream");
map.keySet().stream().forEach(key -> {System.out.print ("Key=" + key + " Value=" + map.get(key)); });
forEach
Following code traverse using forEach method. forEach method was introduced in java 8.
System.out.println("\nPrint using forEach");
map.forEach((k, v) ->System.out.print( "Key=" + k + " Value=" + v)) ;

Table of Content

removeEldestEntry() Method in Java

LinkedHashMap in Java stores key-value pairs and maintains the order of elements inserted. LinkedHashMap extends HashMap. Method removeEldestEntry in LinkedHashMap is used to delete the old entry in the map automatically. This method is triggered when we put values to the map.
removeEldestEntry() method is triggered when we put new items to map. It is a boolean method and accepts one parameter. We can override this method to decide whether and when to remove eldest entries from the map.

Examples

LinkedHashMap Simple
Following is a simple LinkedHashMap which is created with initial size 10. And then later added 6 Items to it. When we print the map it prints {0=A, 1=B, 2=C, 3=D, 4=E, 5=F}
LinkedHashMap map;
map = new LinkedHashMap(10 , 0.7f, false);
map.put(0, "A"); 
map.put(1, "B"); 
map.put(2, "C"); 
map.put(3, "D"); 
map.put(4, "E"); 
map.put(5, "F");

System.out.println(map); //{0=A, 1=B, 2=C, 3=D, 4=E, 5=F}
LinkedHashMap with removeEldestEntry
Here we implement the protected method removeEldestEntry and return true if size is more than 4. As a result this map will automatically delete one of the oldest entry when its size becomes more than 4. That's why even though we are adding 6 items to it, when we print we get only 4 items like {2=C, 3=D, 4=E, 5=F}
LinkedHashMap map;

map = new LinkedHashMap(10 , 0.7f, false) {
  protected boolean removeEldestEntry(Map.Entry eldest) {
    return size()>4;
  }
};

map.put(0, "A"); 
map.put(1, "B"); 
map.put(2, "C"); 
map.put(3, "D"); 
map.put(4, "E"); 
map.put(5, "F");

System.out.println(map); //{2=C, 3=D, 4=E, 5=F}
Notes
  • LinkedHashMap maintains the insertion order of the values.
  • If removeEldestEntry returns false then no items will ever be removed from the map and it will essentially behave like a normal Map.
  • If removeEldestEntry returns true then it will not let any item's get added to the map.
  • removeEldestEntry is a protected method that's why we can only implement it while creating the map.