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

Saturday, 10 October 2020

Java Stream API: anyMatch(), allMatch(), and noneMatch() with Examples

          Java 8 introduced many powerful features, and the Stream API is one of the most important because it simplifies data processing and makes the code more concise and readable. In this post, we will explore the anyMatch(), allMatch(), and noneMatch() methods with examples.
  • anyMatch() – Returns true if at least one element in the stream matches the given predicate; otherwise, it returns false.

  • allMatch() – Returns true if all elements in the stream match the given predicate; otherwise, it returns false.

  • noneMatch() – Returns true if none of the elements in the stream match the given predicate; otherwise, it returns false.

Example:

package com.practice;

import java.util.ArrayList;
import java.util.List;

public class StreamMatchExample {

	public static void main(String[] args) {

		List<Employee> employeeList = new ArrayList<>();
		employeeList.add(new Employee("Mahesh", "Male", "abc@gmail.com"));
		employeeList.add(new Employee("Sathish", "Male", "abc@gmail.com"));
		employeeList.add(new Employee("Mahesh", "Male", "abc@gmail.com"));
		employeeList.add(new Employee("Pooja", "Female", "abc@gmail.com"));

		boolean allMatch = employeeList.stream().allMatch(
                               emp -> emp.getEmail().equalsIgnoreCase("abc@gmail.com"));
		System.out.println("allMatch - " + allMatch);

		boolean anyMatch = employeeList.stream().anyMatch(
                               emp -> emp.getName().equalsIgnoreCase("Mahesh"));
		System.out.println("anyMatch - " + anyMatch);

		boolean noneMatch = employeeList.stream().noneMatch(
                               emp -> emp.getName().equalsIgnoreCase("Anil"));
		System.out.println("noneMatch - " + noneMatch);
	}

}
 
Output :--
allMatch - true
anyMatch - true
noneMatch - true

Related Posts:-

Thursday, 5 April 2018

Implementation of Merge Sort in Java

          In previous post, implemented the Selection Sort in JavaIn this post, we can implement the merge sort and also discuss the time complexity.

          Merge Sort is a fast, recursive, stable sort algorithm which works by the divide and conquer principle. The algorithm has a complexity of O(n log (n)). Merge Sort is similar to Quick Sort(Will implement in the next post) the list of elements which should be sorted is divided into two lists. These lists are sorted independently and then combined together. During the combination of the lists the elements are inserted (or merged) on the correct place in the list.

It involves the following steps,
  • Divide the array into two (or more) sub arrays.
  • Sort each sub array (Conquer).
  • Merge them into one (in a smart way)
See the below diagram,

merge sort in java

MergeSort.java,

package com.test;

public class MergeSort {
        private int[] arr;
        private int[] temp;
        private int length;
     
        public static void main(String a[]){
             int[] arr = {60,8,44,71,33,96,12,10,46};
  
             System.out.println("Array before sorting:--");
             for(int i=0;i < arr.length;i++){
                  System.out.println(arr[i]);
             } 
  
             MergeSort mers = new MergeSort();
             mers.sort(arr);
        
             System.out.println("Array after sorting:--");
             for(int i:arr){
                  System.out.println(i);
             }
        }
    
        public void sort(int arr[]) {
             this.arr = arr;
             this.length = arr.length;
             this.temp = new int[length];
             MergeSortArr(0, length - 1);
        }
    
        private void MergeSortArr(int lowIndex, int highIndex) {
             if (lowIndex < highIndex) {
                  int middle = lowIndex + (highIndex - lowIndex) / 2;
                  MergeSortArr(lowIndex, middle);
                  MergeSortArr(middle + 1, highIndex);
                  MergeSortArr1(lowIndex, middle, highIndex);
             }
        }
    
        private void MergeSortArr1(int lowIndex, int middle, int highIndex) {
             for (int i = lowIndex; i <= highIndex; i++) {
                    temp[i] = arr[i];
             }
             int i = lowIndex;
             int j = middle + 1;
             int k = lowIndex;
             while (i <= middle && j <= highIndex) {
                  if (temp[i] <= temp[j]) {
                       arr[k] = temp[i];
                       i++;
                  } else {
                      arr[k] = temp[j];
                      j++;
                 }
                 k++;
             }
             while (i <= middle) {
                 arr[k] = temp[i];
                 k++;
                 i++;
             }
 
        }
 }

Output:--
Array before sorting:--
60
8
44
71
33
96
12
10
46
Array after sorting:--
8
10
12
33
44
46
60
71
96

Thank you for visiting the blog.

Saturday, 10 March 2018

Java Program to Check Whether a Binary Tree Is a Binary Search Tree (BST)

           In the previous post, we discussed the height of a Binary Search Tree (BST). In this post, we will learn how to write a Java program to validate whether a given binary tree is a Binary Search Tree (BST).

In a binary tree, each node can have at most two child nodes. For a binary tree to qualify as a Binary Search Tree (BST), the following conditions must be satisfied:

  • All nodes in the left subtree of a node must have values less than or equal to the value of that node.

  • All nodes in the right subtree of a node must have values greater than the value of that node.

If every node in the tree satisfies these conditions, then the binary tree is a valid Binary Search Tree (BST).


BSTValidation.java,

package com.practice;

class Node {
 
      int data;
      Node leftChild;
      Node rightChild;
 
      public Node(int data) {
           this.data = data;
           leftChild = null;
           rightChild = null;
      }
}

public class BSTValidation {
      Node root;
      public boolean isBinarySearchTree() {
   
            if(root == null) return Boolean.TRUE;
            return isBstValid(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
      }
 
      private boolean isBstValid(Node node, Integer minValue, Integer maxValue) {
 
            if(node == null) return Boolean.TRUE;
            if(node.data >= minValue && node.data < maxValue
                  && isBstValid(node.leftChild, minValue, node.data)
                  && isBstValid(node.rightChild, node.data, maxValue)) {
                    return Boolean.TRUE;
            } else {
                    return Boolean.FALSE;
            }
      }
    
      public static void main(String[] args) {
               
             BSTValidation tree = new BSTValidation();
        
             // first example, valid binary search tree
             tree.root = new Node(48);
             tree.root.leftChild = new Node(22);
             tree.root.rightChild = new Node(61);
             tree.root.leftChild.leftChild = new Node(12);
             tree.root.leftChild.rightChild = new Node(28);
             tree.root.rightChild.leftChild = new Node(54);
             tree.root.rightChild.rightChild = new Node(68);
             System.out.println(tree.isBinarySearchTree());
     
             // second example, not a valid bst
     
             tree.root = new Node(48);
             tree.root.leftChild = new Node(22);
             tree.root.rightChild = new Node(100);
             tree.root.leftChild.leftChild = new Node(12);
             tree.root.leftChild.rightChild = new Node(28);
             tree.root.rightChild.leftChild = new Node(54);
             tree.root.rightChild.rightChild = new Node(68);
             System.out.println(tree.isBinarySearchTree());
      }
}

Output : true
               false



Related Post:
1) Program to find the height of Binary Search Tree(BST) in Java
2) Program to find maximum and minimum value from Binary Search Tree in Java
3) Java Program to delete a node from Binary Search Tree(BST)
4) Java Program to Count the number of nodes and leaf nodes of Binary Tree
5) How to Remove duplicates from ArrayList in Java

Monday, 5 March 2018

Program to find the height of Binary Search Tree(BST) in Java

           In previous post, discussed about to max and min value of BST. In this post, we will see how to find the height of binary search tree.

          Height of binary tree is number of edges from root  node to deepest leaf node. Height of empty tree is 0.

See the below BST,  Height of BST is 4.
Height of Binary Search Tree
Height of Binary Search Tree

BSTHeightCalc.java, Using recursion

package com.practice;

class Node {
 
      int data;
      Node leftChild;
      Node rightChild;
 
      public Node(int data) {
           this.data = data;
           leftChild = null;
           rightChild = null;
      }
}

public class BSTHeightCalc {
 
      Node root;
 
      int calcBSTHeight() {
            return calcBSTHeight(root);
      }
 
      int calcBSTHeight(Node node) {
            if (node == null) {
                  return 0;
            }
  
            return Math.max(calcBSTHeight(node.leftChild), calcBSTHeight(node.rightChild))+1;
      }
 
      public static void main(String[] args) {
              BSTHeightCalc height = new BSTHeightCalc();
              height.root = new Node(18);
              height.root.leftChild = new Node(12);
              height.root.rightChild = new Node(28);
              height.root.leftChild.rightChild = new Node(32);
              System.out.println("Height of the BST:-"+height.calcBSTHeight());
      }
}

Output :--  Height of the BST:-3



Related post:--
1)  Program to find maximum and minimum value from Binary Search Tree in Java
2) Java Program to delete a node from Binary Search Tree(BST)
3) Java Program to Count the number of nodes and leaf nodes of Binary Tree
4) Java Program to Reverse a Linked List using Recursion and Loops

Friday, 2 March 2018

Java Program to Find the Maximum and Minimum Values in a Binary Search Tree (BST)

          In the previous post, we discussed how to delete a node from a Binary Search Tree (BST). In this post, we will learn how to find the minimum and maximum values in a Binary Search Tree.

Keep in mind: In a BST, the value of every node in the left subtree is less than or equal to the value of the root node, and the value of every node in the right subtree is greater than the value of the root node.

To find the minimum value in a BST, simply traverse the left child of each node until you reach the leftmost node. The leftmost node contains the minimum value.

Similarly, to find the maximum value, traverse the right child of each node until you reach the rightmost node. The rightmost node contains the maximum value.

Consider the following BST:

Min and Max value in BST
Minimum and Maximum value in BST


MaxMinBSTNode.java

package com.test;

public class Node {

        Integer data;
        Node leftChild;
        Node rightChild;
 
        public Node(Integer data) {
              this.data = data;
              leftChild = null;
              rightChild = null;
        }
}


public class MaxMinBSTNode {
 
        Node root;

        private Integer getMaxNode() {
               return getMaxNode(root);
        }
 
        private Integer getMinNode() {
               return getMinNode(root);
        }
 
        private Integer getMaxNode(Node node) {
  
               if (node.rightChild != null) {
                      return getMaxNode(node.rightChild);
               } 
               return node.data;
        }
 
        private Integer getMinNode(Node node) {
               if(node.leftChild != null) {
                      return getMinNode(node.leftChild);
               }
               return node.data;
        }
 
        public static void main(String[] args) {
  
                 MaxMinBSTNode tree = new MaxMinBSTNode();
                 tree.root = new Node(22);
                 tree.root.leftChild = new Node(10);
                 tree.root.rightChild = new Node(30);
                 tree.root.leftChild.leftChild = new Node(6);
                 tree.root.leftChild.rightChild = new Node(14);
                 tree.root.rightChild.leftChild = new Node(27);
                 tree.root.rightChild.rightChild = new Node(32);
  
                 System.out.println("Max value:--"+tree.getMaxNode());
                 System.out.println("Min value:--"+tree.getMinNode());
        }
}

Output:-- Max value:-- 32
                 Min value:--6



Related Post:--
1) Java Program to delete a node from Binary Search Tree(BST)
2) Java Program to Count the number of nodes and leaf nodes of Binary Tree
3) Java Program to Reverse a Linked List using Recursion and Loops
4) How to Remove duplicates from ArrayList in Java
5) Java Program to Count Occurrence of Word in a Sentence

Wednesday, 28 February 2018

Java Program to Delete a Node from a Binary Search Tree (BST)

       In the previous post, we discussed leaf nodes and the total number of nodes in a Binary Search Tree (BST). In this post, we will learn how to delete a node from a Binary Search Tree.

There are three scenarios to consider when deleting a node from a Binary Search Tree:

  1. The node has no children (i.e., it is a leaf node).

  2. The node has one child.

  3. The node has two children.


1) If node has no child(i.e leaf node)
       
It is easy and straight forward, Just We need to search the node and make it null.

Delete a node has no child
Example:--

2) If node has one child

     If node have one children then we need to connect parent of removed node directly to child of the removed node.
Example:-
Delete a node have one child


3)  If node has two children

     It is somewhat complicated to delete the node.  If it has two nodes, we need to connect parent of node to the leftmost node(minimum) of right sub tree or rightmost node(maximum) of left sub tree.
Example:--
Delete two child of Binary Tree

Java Program to Delete the Node from a Binary Tree.

BSTDeleteNode.java


package com.test;

class Node {
     
     Integer data;
     Node leftChild;
     Node rightChild;
 
     public Node(Integer data) {
           this.data = data;
           leftChild = null;
           rightChild = null;
     }
}

public class BSTDeleteNode {
 
       Node root;

       Node deleteNode(Integer data) {
            return deleteNode(root, data);
       }
       Node deleteNode(Node node, Integer data) {
            if (node == null) 
                 return node;
            if (data < node.data) {
                 node.leftChild = deleteNode(node.leftChild, data);
            } else if(data > node.data) {
                 node.rightChild = deleteNode(node.rightChild, data);
            } else {
                //node with only one child or no child
                 if (node.leftChild == null) {
                       return node.rightChild;
                 } else if(node.rightChild == null) {
                       return node.leftChild;
                 }
                 //node with two children, smallest in the right subtree
                 node.data = minValue(node.rightChild);
   
                 node.rightChild = deleteNode(node.rightChild, node.data);
   
           }
  
           return node;
      }
 
      int minValue(Node root) {
            int minv = root.data;
            while (root.leftChild != null) {
                minv = root.leftChild.data;
                root = root.leftChild;
            }
            return minv;
       }
 
       /*  To Print the given Node data
       */
       void inorderRec() {
             inorderRec(root);
       }
 
       void inorderRec(Node root) {
             if (root != null) {
                  inorderRec(root.leftChild);
                  System.out.print(root.data + " ");
                  inorderRec(root.rightChild);
             }
        }
 
        public static void main(String[] args) {
  
                BSTDeleteNode tree = new BSTDeleteNode();
                tree.root = new Node(10);
                tree.root.leftChild = new Node(6);
                tree.root.rightChild = new Node(16);
                tree.root.leftChild.leftChild = new Node(4);
                tree.root.leftChild.rightChild = new Node(8);
                System.out.println("Printing node before delete,");
                tree.inorderRec();
                tree.deleteNode(16);      //delete node method
                System.out.println("");
                System.out.println("Printing node after delete,");
                tree.inorderRec();
       }
}

Output :-
Printing node before delete,
4 6 8 10 16
Printing  node after delete,
4 6 8 10




Related Post:--
1) Java Program to Count the number of nodes and leaf nodes of Binary Tree
2) Java Program to Reverse a Linked List using Recursion and Loops
3) How to Remove duplicates from ArrayList in Java
4) Java Program to Count Occurrence of Word in a Sentence
5) How to iterate the TreeMap in reverse order in Java