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.