​
Showing posts with label structure. Show all posts
Showing posts with label structure. Show all posts

Friday, 30 June 2017

Creating your own loop structure in Java 8 lambda

Creating your own loop structure in Java 8 lambda


Java doesnt have an easy construct of repeat something N number of times. We can make a for loop of course, but many times we dont even care about the variable that we created in the loop. We just want repeat N times of some code and thats it. With the lambda available in Java 8, you may attempt something like this:

public class RepeatDemo {
    public static void main(String[] args) {

        // One liner repeat
        repeat(10, () -> System.out.println("HELLO"));


        // Multi-liners repeat

        repeat(10, () -> {
            System.out.println("HELLO");
            System.out.println("WORLD");
        });
    }
   
    static void repeat(int n, Runnable r) {
        for (int i = 0; i < n; i++)
            r.run();
    }
}



Probably not as eye pleasing or straight forward as the good fashion for-loop, but you do get rid of the unnecessary loop variable. Only if Java 8 would go extra mile and treat the lambda argument in method with sugar syntax, then we could have it something like the Scala/Groovy style, which makes code more smoother. For example:

        // Wouldnt this be nice to have in Java?

        repeat(10) {
            System.out.println("HELLO");
            System.out.println("WORLD");
        }


Hum....
{ Read More }


Saturday, 22 April 2017

copy directory structure copy files with directories

copy directory structure copy files with directories


Q. How can I copy a directory tree without copying files?
A. Enter the root of the tree you want to copy. The tree will be recreated under /destination/
$ find -type d | xargs -i mkdir -p  /destination/{}


Q. How can I copy the files and recreate the directory tree the file is in. I.E. copy the file along with the whole or part of the directory tree.
A. Enter the folder you want to be the root of the copied tree. Suppose I have /home/me/work/urgent/files/x.htm copied to /destination/ starting from me/ folder. Enter /home/ and type:
$ echo  me/work/urgent/files/x.htm | cpio -pdvm /destination/
#search for files and copy all found with their dir trees
$ find . -name *.htm |cpio -pdvm /destination/
{ Read More }