Lambda, Stream, Method Reference, and Multithreading All in one simple program

This code sums up Lambda, Stream, Method Reference and Multithreading all in one.


import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.IntPredicate;

/**
 *
 * @author Aamir khan
 */
public class Count {

    private String userinpt = "";
    private final List<runnable> tasks;

    public static void main(String[] args) {
        Count c = new Count();
        c.takeInput();
        c.start();
    }

    /**
    * init the list of tasks
    **/
    Count() {
    //Lambda in action
        tasks = Arrays.asList(
                () -> countVowels(),
                () -> countCons(),
                () -> countDigits(),
                () -> countWhiteSpace()
        );

    }

    /**
     * take user input used by
     * {@link #count(java.util.function.IntPredicate)};
     *
     */
    private void takeInput() {

        System.out.println("Enter your Text");
        userinpt = new Scanner(System.in).useDelimiter("\\z").next();

    }

    /***
    * submit the task to Thread pool and execute them.
    */
    private void start() {
    //Multithreading in action
        ExecutorService thread = Executors.newFixedThreadPool(tasks.size());
        tasks.forEach(thread::submit);
        thread.shutdown();
    }

    private void countVowels() {
    //Method Reference in action
        long numberOfVowels = count(this::isVowel);
        print("Total number of Vowels: " + numberOfVowels);

    }

    private void countWhiteSpace() {
        long numberOfWhiteSpaces = count(Character::isWhitespace);
        print("Total number of Spaces: " + numberOfWhiteSpaces);
    }

    private void countDigits() {
        long numberOfDigits = count(Character::isDigit);
        print("Total number of Digits: " + numberOfDigits);

    }

    private void countCons() {
        long numberOfCons = count(e -> Character.isLetter(e) && !isVowel(e));
        print("Total number of Consonants: " + numberOfCons);

    }

    /**
    * filter with given Predicate and count the filtered result
    **/
    private long count(IntPredicate filter) {
        // Stream in action    
        return userinpt.toLowerCase().chars().filter(filter).count();
    }
    
    
    
    //util methods
    public boolean isVowel(int codePoint) {
        //checking for lower case because the input will only be in lower case
        return (codePoint == 'a')
                || (codePoint == 'e')
                || (codePoint == 'i')
                || (codePoint == 'o')
                || (codePoint == 'u');

    }

    public void print(String s) {
        System.out.println(s);
    }
}

No comments :

Post a Comment