Include conditional dependencies and packages in gradle

I got a task in my project to add some dependencies on need basis.

We are creating a jar for different tools, lots of code we have common but some of code and dependencies required for jar is not needed for other.

Before directly jumping into actual code base I wanted get my hand dirty in some dummy project, So I have spent some time to understands gradle tasks and dependency management and created the dummy project.

I am rewriting here for my own benefit and yours as well.

We can add dependencies by providing build time argument

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    if(project.property("build").equals("build1")){
        println "Including dependencies of build1"
        compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.0'
    }
    if (project.property("build").equals("build2")){
        println "Including dependencies of  build2"
        compile group: 'com.google.code.gson', name: 'gson', version: '2.7'
    }
}


To add the conditional dependency we need to run our build command
gradle build -Pbuild="build1"
Or
gradle build -Pbuild="build2"


We can create the separate task for separate Jars.

Task build the Jar for Build1:-
task build1Jar(type: Jar){
    from sourceSets.main.output

    exclude '**/package2/**'

    manifest {
        attributes(
                "Manifest-Version": "1.0",
                "Main-Class" : "com.ravat.package1.Runner",
                "Class-Path":  configurations.runtimeClasspath.collect { it.getName() }.join(' ')
        )
    }
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
    baseName = 'build1'
}

Task build the Jar for Build2:-
task build2Jar(type: Jar){
    from sourceSets.main.output

    exclude '**/package1/**'

    manifest {
        attributes(
                "Manifest-Version": "1.0",
                "Main-Class" : "com.ravat.package2.Runner",
                "Class-Path":  configurations.runtimeClasspath.collect { it.getName() }.join(' ')
        )
    }
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
    baseName = 'build2'
}

To create a jar with required dependencies and package we need to run the following gradle command
gradle clean install build1Jar
or
gradle clean install build2Jar 

Magic of bit manipulation : fastest way to swap two variables

We all have faced this question in our interview process to swap 2 variables.

If not faces while working with arrays we may have faced to swap 2 variables in array.

I hope, you all know the concept of swapping 2 variables. today I am going to show you the fastest way to swap two variables.

We all know data is stored in computer memory in the form of bits(0 & 1), that means all the operation we do on the bits will be perform faster by computer.

some bit manipulation examples :-

Bitwise XOR operator :-

value  ^ 0s         ==   value 
value  ^ 1s         ==  ~value
value  ^ value      ==   0s

Bitwise AND Operator :-

value  &  0s      ==  0s 
value  &  1s      ==  value
value  &  value   ==  value

Bitwise OR Operator :-

value  |  0s       ==  value 
value  |  1s       ==  1s
value  |  value    ==  value

We will use XOR Operator to swap 2 variable :-

x = 10
y = 12

8 4 2 1
1 0 1 0  = 10(x)
1 1 0 0  = 12(y)

x = x ^ y  1010^1100 = 0110
y = x ^ y  0110^1100 = 1010 (10)
x = x ^ y  0110^1010 = 1100 (12)

We will implement a bubble sort algorithm to see the benefit of bit manipulation:-

import java.util.Arrays;

public class BubbleSort {
    public static void main(String[] args) {
        int[] array = new int[]{20,35,-15,7,55,1,-22};
        array = bubbleSort(array);
        System.out.println(Arrays.toString(array));
    }

    private static int[] bubbleSort(int[] array) {
        for (int i=0;i<array.length;i++){                       
            for (int j=0;j < array.length-i-1;j++) {             
                if (array[j] > array[j+1]){                       
                    //fastest way to swap two variable
                    array[j] = array[j] ^ array[j+1];
                    array[j+1] = array[j] ^ array [j+1];
                    array[j] = array[j] ^array[j+1];
                }
            }
        }
        return array;
    }
}

How can use HashSet to solve Array related Problems

Today I was solving some array related problems on GeeksForGeeks,

Came across with solution How Hashset helped me to solve these problems for large amount of input within given time complexity.

Here is the problem statements I have solved:-

Problem Statement:- Pair with given sum in a sorted array

Solution :-
import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {
    public static void main (String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine());
        while(T --> 0){
            int N = Integer.parseInt(br.readLine());
           
            String str = br.readLine();
            String[] inputArr = str.trim().split("\\s+");
            int A[] = new int[N];
            for(int i=0;i<N;i++){
                A[i] = Integer.parseInt(inputArr[i]);
            }
            int K = Integer.parseInt(br.readLine());
           
            int low = 0;
            int high = N-1;
            boolean flag = true;
            while(low<high){
                if(A[low]+A[high] > K){
                    high--;
                }else if(A[low]+A[high] < K){
                    low++;
                }else{
                    System.out.println(A[low]+" "+A[high] + " "+ K);
                    low++;
                    flag = false;
                }
            }
            if(flag){
                System.out.println(-1);
            }           
        }
    }
}


Problem Statement:- Triplet Sum in Array

Solution :-
import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {
    public static void main (String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine());
        while(T --> 0){
            String input = br.readLine();
            String[] inputArry = input.trim().split("\\s+");
            int N = Integer.parseInt(inputArry[0]);
            int X = Integer.parseInt(inputArry[1]);
            String arrInp = br.readLine();
            String[] arr = arrInp.trim().split("\\s+");
            int[] A = new int[N];
            for(int i=0;i<N;i++){
                A[i] = Integer.parseInt(arr[i]);
            }
            Set<Integer> sumSet = new HashSet<>();
            boolean flag= true;
            for(int i=0;i<N;i++){
                if(sumSet.contains(X-A[i])){
                    System.out.println("1");
                    flag = false;
                    break;
                }else{
                    for(int j=0;j<=i;j++){
                        sumSet.add(A[i]+A[j]);
                    }
                }
            }
            if(flag){
                System.out.println("0");
            }
        }
    }
}

First non repeating word in string.

public String firstNonRepeatingword(String string) {
        if(string == null || string.isEmpty()) {
            return "No unique word found";
        }else {
            StringTokenizer tokens = new StringTokenizer(string);
            LinkedList<String> list = new LinkedList<>();
            while(tokens.hasMoreTokens()) {
                list.add(tokens.nextToken());
            }
            for(int i=0;i<list.size();i++) {
                if (Collections.frequency(list,list.get(i)) == 1) {
                    return list.get(i);
                }
            }
        }
        return "No unique word found";
    }

It's up to you how are you spliting the string there are many ways, If you have small string tokenizer is fast.

Performance of StringTokenizer class vs. String.split method vs indexOf 

Difference between final and effectively final


final variable: A variable or parameter is declared as final and whose value is never changed after it is initialized is final.

effectively final variable: A variable or parameter is not declared as final and still the whose value is never changed after it is initialized is effectively final.
public class Demo {
 public static void main(String[] args) {
 int count = 0;
 List list = new ArrayList() {{
    add("employee1"); 
    add("employee2"); 
    add("employee3"); 
    add("employee4"); 
 }}; 
 list.stream().forEach(str -> { count++; });
 } 
}
here the error on count++ :-
Local variable count defined in an enclosing scope must be final or effectively final.

here the variable count is not declared as final but it is still a final variable and its value will not be changed, the count varibale here is effectively final variable

Functional programming with Java - Part 1

 Recently I was reviewing one PR raised by team memeber and going through one utitlity method and found out there are too many muatable vari...