In this post, we will see how to find second largest number in an array.

Problem :

Given an unsorted array, you need to find second largest element in the array in o(n) time complexity.
For example:
int[] arr1={7,5,6,1,4,2};
Second largest element in the array : 6

Solution:

You can sort the array and then return second last element in the array but it will be done in o(nlogn) time,

Algorithm:

  • Initialize highest and secondHighest with minimum possible value.
  • Iterate over array.
  • If current element is greater than highest
    • Assign secondHighest = highest
    • Assign highest = currentElement
  • Else if current element is greater than secondHighest 
    • Assign secondHighest =current element.

Java Program to find second largest number in array:

Create a main java class named "FindSecondLargestMain.java".
package org.arpit.java2blog;

public class FindSecondLargestMain {
 public static void main(String args[])
 {
  int[] arr1={7,5,6,1,4,2};
  int secondHighest=findSecondLargestNumberInTheArray(arr1);
  System.out.println("Second largest element in the array : "+ secondHighest);
 }
 
 public static int findSecondLargestNumberInTheArray(int array[])
 {
  // Initialize these to the smallest value possible
  int highest = Integer.MIN_VALUE;
  int secondHighest = Integer.MIN_VALUE;

  // Loop over the array
  for (int i = 0; i < array.length; i++) {

    // If current element is greater than highest
      if (array[i] > highest) {

          // assign second highest element to highest element 
          secondHighest = highest;

          //  highest element to current element
          highest = array[i];
      } else if (array[i] > secondHighest)
          // Just replace the second highest
          secondHighest = array[i];
      }
  

  // After exiting the loop, secondHighest now represents the second
  // largest value in the array
 return secondHighest;
 }
}
When you run above program, you will get below output:
Second largest element in the array : 6

I have been posting data structure and algorithms programs on various topics such as Array,Queue, Stack ,Binary tree, LinkedList , String, Number, ArrayList, etc. So I am consolidating list of programs to create an index post. I will keep adding links to this post whenever I add any new program. These are frequently asked Data Structure and algorithm programs in interview.

If you want to practice and improve data structure and algorithm programs, this post will be very helpful to you. I will recommend you to try it yourself first and then check the solution.

Stack :

Question 1:  Implement a stack using array.

You need to implement Stack using array. You need to write push and pop methods to demonstrate Stack behavior(Last In First Out).
Solution : Java Program to implement stack using array.

Question 2: Implement a stack using Linked List :

You need to implement Stack using Linked List. You need to write push and pop methods to demonstrate Stack behavior(Last In First Out).
Solution  Java Program to implement stack using Linked List

Question 3:  Implement a stack using two queues .

You need to use two queues to implement stack behavior.You need to write push and pop methods to demonstrate Stack behavior(Last In First Out).
Solution : Java Program to implement stack using two queues

Question 4 :  Sort an stack using another stack

You need to sort an stack using another stack. You can use push and pop operation of stack to do so,
Solution : Sort a stack using another stack.

Linked List :

Question 5 : Implement singly linked list in java.

You need to implement singly linked list data structures.You need to write simple program to demonstrate insert , delete operations.

Solution : Java program to implement singly linked list in java.

Question 6: How to reverse linked list in java.

You need to write iterative and recursive solution to reverse linked list.
Solution : Java program to reverse linked list in java.

Question 7: How to find middle element of linked list.

You need to write java program to find middle element of linked list in most optimize way.


Solution : Java program to find middle element of linked list.

Question 8 : How to find nth element from end of linked list .

You need to write java program to find nth  element of linked list in most optimize way.
In question 6, Node 7 is 3rd from last of linked list.
Solution : How to find nth element from end of linked list.

Question 9  : How to detect a loop in linked list. If linked list has loop, find the start node for the loop.

You need to write a java program to detect whether any loop exists in linked list and if loop exists , you need to find start node for the linked list.
Solution : How to detect loop in linked list.
How to find start node of loop in linked list.

Question 10: How to check if linked list is palindrome or not?

A palindrome is a word, phrase, number, or other sequence of symbols or elements that reads the same forward or reversed. For example: 12121 is palindrome as it reads same forward or reversed. madam is also a palindrome . So we need write java programs to check if linked list is palindrome or not.
Solution : Java program to check if linked list is palindrome.

Question 11 :  How to reverse a linked list in pairs?

You need to write a java program to reverse linked list in pairs.
Solution  : Java program to reverse linked list in pair.

Binary Tree :

Question 12: How can you traverse binary tree?

There are three ways to traverse binary tree.

Question 13 : Write an algorithm to do level order traversal of binary tree?

You need to write java program to do level order traversal of binary tree. You can use queue data structure to do level order traversal.

Question 14 :  Write an algorithm to do spiral order traversal of binary tree?

You need to write java program to do spiral level order traversal of binary tree

Solution Sprial order or zigzag traversal of binary tree.

Question 15: How can you print leaf nodes of binary tree?

You need to write java program to print all leaf nodes of binary tree.
Leaf nodes for above binary tree will be 5 , 30 , 55 ,70
Solution : Print leaf nodes of binary tree.

Question 16: How to count leaf nodes of binary tree.

You need to write java program to count leaf nodes of binary tree.
Count of Leaf nodes for binary tree used in Question 15 are 5.
Solution : Count leaf nodes of binary tree.

Question 17. How to print all paths from root to leaf in binary tree.

You need to write a program to print all paths from root to leaf.
Solution : Print all paths from root to leaf in binary tree.

Question 18 : How to find level of node in binary tree

Given a node, you need to find level of a node. For example : Level of node will 3 for node 70 used in Question 14.
Solution: Find level of node in binary tree.

Question 19: How to find maximum element in binary tree.

You need to write a java program to find maximum element in binary tree.
Solution : Find maximum element in binary tree.

Question 20 : How to find lowest common ancestor(LCA) in binary tree.

You need to write a program to find LCA in binary tree.
Solution: Program to find LCA in binary tree.

Question 21 : How to do boundary traversal of binary tree.

Write a java program to do boundary traversal of binary tree as shown in below image.
Solution : Boundary traversal of binary tree.

Question 22 : How to print vertical sum of binary tree?

You need to find sum of nodes which lies in same column.
Solution : How to print vertical sum of binary tree.

Binary Search tree:

Question 23 : What is binary search tree?

Binary search tree is a special type of binary tree which have following properties.
  • Nodes which are smaller than root will be in left subtree.
  • Nodes which are greater than root will be right subtree.
  • It should not have duplicate nodes
  • Both left and right subtree also should be binary search tree.

Question 24: Can you write algorithm to insert a node in binary search tree.

Solution : Insert node in binary search tree.

Question 25: Can you write algorithm to delete a node in binary search tree.

Solution : Delete node in binary search tree.

Question 26:  How can you find minimum and maximum elements in binary search tree?

Solution : Leftmost and rightmost nodes of binary search tree are minimum and maximum nodes respectively

Question 27 : How to find lowest common ancestor(LCA) in binary search tree.

You need to write a program to find LCA in binary search tree.
SolutionProgram to find LCA in binary search tree.

Sorting :

Question 28 : Can you write algorithm for merge sort and also do you know complexity of merge sort?

Question 29 : What is binary search? Can you write an algorithm to find an element in sorted array using binary search?

Array:

Question 30  : Find missing number in the array.

You are given an integer array containing 1 to n but one of the number from 1 to n in the array is missing. You need to provide optimum solution to find the missing number. Number can not be repeated in the arry.
For example:
int[] arr1={7,5,6,1,4,2};
Missing numner : 3
int[] arr2={5,3,1,2};
Missing numner : 4
Solution : Find missing number in the array.

Question 31 : Search an element in rotated and sorted array.

You are given an sorted and rotated array as below:
int arr[]={16,19,21,25,3,5,8,10};
If you note that array is sorted and rotated. You need to search an element in above array in o(log n) time complexity.
Solution : Search element in rotated and sorted array

Graph:

Question 32 : Write algorithm to do depth first search in a graph.

Question 33: Write algorithm to do breadth first search in a graph.

Miscellaneous

Question 34 : What is an algorithm and how to calculate complexity of algorithms.

Solution : How to calculate Complexity of algorithm.

String: 

You can find list of interview programs on String.

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm programs.
In this post,  we will see how to sort a stack using another stack.

Problem :

Given a Stack,  you need to sort it with the help of temporary stack.

Solution :

  • Let's say,  you have two stacks,  stack  and tempStack. 
  • Pop an element from stack and compare it with head of tempStack. 
  • If element it greater, push it to tempStack. 
  • If element is lesser than  head of tempStack, pop the element from tempStack and push it to stack until you get the element which is greater than head of tempStack. 
  • In the end,  tempStack will be sorted stack. 

Java code:

public static StackCustom sortStack(StackCustom stack)
 {
  StackCustom tempStack = new StackCustom(10);
  while(!stack.isEmpty())
  {
   int currentData=stack.pop();
   while(!tempStack.isEmpty() && tempStack.peek() > currentData) {
    stack.push(tempStack.pop());
         }
   tempStack.push(currentData);
  }
  return tempStack;
 }

Complete Java program to sort a stack using addition stack:

package org.arpit.java2blog;
/**
 * @author Arpit Mandliya
 */
public class StackCustom {
 int size;
 int arr[];
 int top;

 StackCustom(int size) {
  this.size = size;
  this.arr = new int[size];
  this.top = -1;
 }

 public void push(int pushedElement) {
  if (!isFull()) {
   top++;
   arr[top] = pushedElement;
  } else {
   System.out.println("Stack is full !");
  }
 }

 public int pop() {
  if (!isEmpty()) {
   int returnedTop = top;
   top--;
   return arr[returnedTop];

  } else {
   System.out.println("Stack is empty !");
   return -1;
  }
 }

 public int peek() {
  return arr[top];
 }

 public boolean isEmpty() {
  return (top == -1);
 }

 public boolean isFull() {
  return (size - 1 == top);
 }

 public static void main(String[] args) {
  StackCustom stackCustom = new StackCustom(10);
  System.out.println("=================");
  stackCustom.push(10);
  stackCustom.push(30);
  stackCustom.push(50);
  stackCustom.push(40);
  stackCustom.printStack(stackCustom);
  StackCustom sortedStack=sortStack(stackCustom);
  System.out.println("=================");
  System.out.println("After Sorting :");
  System.out.println("=================");
  sortedStack.printStack(sortedStack);
  
 }

// Sort a stack using another stack 
public static StackCustom sortStack(StackCustom stack)
 {
  StackCustom tempStack = new StackCustom(10);
  while(!stack.isEmpty())
  {
   int currentData=stack.pop();
   while(!tempStack.isEmpty() && tempStack.peek() > currentData) {
    stack.push(tempStack.pop());
         }
   tempStack.push(currentData);
  }
  return tempStack;
 }
 
 public  void printStack(StackCustom stack)
 {
 if(top>=0)
 {
  System.out.println("Elements of stacks are:");
  for (int i = 0; i <= top; i++) {
   System.out.println(arr[i]);
  }
 }
 
 }
}
When you run above program, you will get below output
=================
Elements of stacks are:
10
30
50
40
=================
After Sorting :
=================
Elements of stacks are:
10
30
40
50

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm programs.
In this post , we will see how to find length of Linked List in java.
You can obviously use size() method of java Linked List class but here we are going to see how to find length of Linked List when you implement Linked List yourself.
There are two ways to find length of linked list:
  • Iterative
  • Recursion

Iterative:

You can iterate over next nodes until node is null and use counter to count number of iteration and you will get length of linked list in the end.
// Find length of linked list using iterative method
public int lengthOfLinkedList()
 {
  Node temp=head;
  int count = 0;
  while(temp!=null)
  {
   temp=temp.next;
   count++;  
  }
  return count;

Recursion: 

You can use recursion also to find length of linked list. Base case: If node is null , return 0. This will be base case of our iteration.
// Find length of linked list using recursion
public int lengthOfLinkedList()
 {
  Node temp=head;
  int count = 0;
  while(temp!=null)
  {
   temp=temp.next;
   count++;  
  }
  return count;
Java program to find length of LinkedList: Create a java file named SinglyLinkedList.java.
package org.arpit.java2blog;

class Node {
 public int data;
 public Node next;

 public void displayNodeData() {
  System.out.println("{ " + data + " } ");
 }
}

public class SinglyLinkedList {
 private Node head;
 
 public boolean isEmpty() {
  return (head == null);
 }

 // used to insert a node at the start of linked list
 public void insertFirst(int data) {
  Node newNode = new Node();
  newNode.data = data;
  newNode.next = head;
  head = newNode;
 }

// Find length of linked list using iterative method
public int lengthOfLinkedList()
{
   Node temp=head;
   int count = 0;
   while(temp!=null)
   {
  temp=temp.next;
  count++;  
   }
    return count;
}
// Find length of linked list using recursion 
public int lengthOfLinkedListRec(Node head)
 {
   Node temp=head;
   if(temp==null)
   {
      return 0;
    }
   else
   {
      return 1+ lengthOfLinkedListRec(temp.next);
    }
}
 // used to delete node from start of linked list
 public Node deleteFirst() {
  Node temp = head;
  head = head.next;
  return temp;
 }

 // used to delete node from start of linked list
 public Node deleteFirst(Node node) {
  Node temp = head;
  head = head.next;
  return temp;
 }

 // Use to delete node after particular node
 public void deleteAfter(Node after) {
  Node temp = head;
  while (temp.next != null && temp.data != after.data) {
   temp = temp.next;
  }
  if (temp.next != null)
   temp.next = temp.next.next;
 }
 
 // used to insert a node at the start of linked list
 public void insertLast(int data) {
  Node current = head;
  while (current.next != null) {
   current = current.next; // we'll loop until current.next is null
  }
  Node newNode = new Node();
  newNode.data = data;
  current.next = newNode;
 }
 
 // For printing Linked List
 public void printLinkedList() {
  System.out.println("Printing LinkedList (head --> last) ");
  Node current = head;
  while (current != null) {
   current.displayNodeData();
   current = current.next;
  }
  System.out.println();
 }
}
Lets create Main class named LinkedListMain.java to create LinkedList.
package org.arpit.java2blog;

public class LinkedListMain {

 public static void main(String args[])
 {
   SinglyLinkedList myLinkedlist = new SinglyLinkedList();
   myLinkedlist.insertFirst(5);
   myLinkedlist.insertFirst(6);
   myLinkedlist.insertFirst(7);
   myLinkedlist.insertFirst(1);
   myLinkedlist.insertLast(2);
   myLinkedlist.printLinkedList();
   // Linked list will be 
   // 2 -> 1 ->  7 -> 6 -> 5
   System.out.println("Length of Linked List using iteration: "+myLinkedlist.lengthOfLinkedList());
   System.out.println("Length of Linked List Using recursion: "+myLinkedlist.lengthOfLinkedListRec(myLinkedlist.getHead()));
 }
}


When you run above program, you will get below output:
Printing LinkedList (head --> last) 
{ 1 } 
{ 7 } 
{ 6 } 
{ 5 } 
{ 2 } 
Length of Linked List using iteration: 5
Length of Linked List Using recursion: 5

In this post, we will see how to implement singly linked list in java.
It is one of the most used data structure. In singly linked list, Node has data and pointer to next node. It does not have pointer to previous node. Last node 's next points to null, so you can iterate over linked list by using this condition.
Node for linked list can be presented as below:
class Node {
 public int data;
 public Node next;

 public void displayNodeData() {
  System.out.println("{ " + data + " } ");
 }
}

Example of linked list:

Lets implement Linked List in java.

Create a java file named SinglyLinkedList.java.
package org.arpit.java2blog;

class Node {
 public int data;
 public Node next;

 public void displayNodeData() {
  System.out.println("{ " + data + " } ");
 }
}

public class SinglyLinkedList {
 private Node head;
 
 public boolean isEmpty() {
  return (head == null);
 }

 // used to insert a node at the start of linked list
 public void insertFirst(int data) {
  Node newNode = new Node();
  newNode.data = data;
  newNode.next = head;
  head = newNode;
 }

 // used to delete node from start of linked list
 public Node deleteFirst() {
  Node temp = head;
  head = head.next;
  return temp;
 }

 // used to delete node from start of linked list
 public Node deleteFirst(Node node) {
  Node temp = head;
  head = head.next;
  return temp;
 }

 // Use to delete node after particular node
 public void deleteAfter(Node after) {
  Node temp = head;
  while (temp.next != null && temp.data != after.data) {
   temp = temp.next;
  }
  if (temp.next != null)
   temp.next = temp.next.next;
 }
 
 // used to insert a node at the start of linked list
 public void insertLast(int data) {
  Node current = head;
  while (current.next != null) {
   current = current.next; // we'll loop until current.next is null
  }
  Node newNode = new Node();
  newNode.data = data;
  current.next = newNode;
 }
 
 // For printing Linked List
 public void printLinkedList() {
  System.out.println("Printing LinkedList (head --> last) ");
  Node current = head;
  while (current != null) {
   current.displayNodeData();
   current = current.next;
  }
  System.out.println();
 }
}
Lets create Main class named LinkedListMain.java to create LinkedList.
package org.arpit.java2blog;

public class LinkedListMain {

 public static void main(String args[])
 {
   SinglyLinkedList myLinkedlist = new SinglyLinkedList();
   myLinkedlist.insertFirst(5);
   myLinkedlist.insertFirst(6);
   myLinkedlist.insertFirst(7);
   myLinkedlist.insertFirst(1);
   myLinkedlist.insertLast(2);
   // Linked list will be 
   // 2 -> 1 ->  7 -> 6 -> 5
   Node node=new Node();
   node.data=1;
   myLinkedlist.deleteAfter(node);
   // After deleting node after 1,Linked list will be 
   // 2 -> 1 -> 6 -> 5
   myLinkedlist.printLinkedList();
 }
}

When you run above program, you will get below output:
Printing LinkedList (head --> last) 
{ 1 } 
{ 6 } 
{ 5 } 
{ 2 } 

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
In this post, we will see how to search an element in sorted and rotated array.

Problem:

You are given an sorted and rotated array as below:
int arr[]={16,19,21,25,3,5,8,10};
If you note that array is sorted and rotated. You need to search an element in above array in o(log n) time complexity.

Solution:

You can search an element in above array using linear search but that will take o(n).
You can use variant of binary search algorithm to solve above problem. You can use a property that you can divide array into two sorted sub arrays ({16,19,21,25},{3,5,8,10} ), although you do not need to find pivot point(Elements start decreasing).

Algorithm:

  • Compute mid i.e low+high/2.
  • Check if a[mid...high] is sorted
    • If number lies between the range , low=mid+1.
    • If number does not lie in the range, high=mid-1.
  • Check if a[low..mid] is sorted.
    • If number lies between the range, high=mid-1..
    • If number does not lie in the range,low=mid+1.
Lets understand this with the help of example.
Search an element in sorted and rotated array
Steps involved to search 5 in above array:
  • Compute mid i.e. 3 (0+7/2)
  • a[mid](25)  >  a[high](10) && 5 < a[low](16) && 5< a[high] (25), so number (5) lies  in right part, so low will become mid+1.
  • a[mid] ==5, so you can return it.

Java program to search an element in a sorted and rotated array :

Create a class named 
SearchElementSortedAndRotatedArrayMain.java.
public class SearchElementSortedAndRotatedArrayMain {

 public static void main(String[] args) {
  int arr[]={16,19,21,25,3,5,8,10};
  System.out.println("Index of element 5 : "+findElementRotatedSortedArray(arr,0,arr.length-1,5));
 }
 public  static  int findElementRotatedSortedArray(int[] arr,int low,int high,int number)
 {
  int mid;
  while(low<=high)
  {
   mid=low + ((high - low) / 2);;
   
   if(arr[mid]==number)
   {
    return mid;
   }
   if(arr[mid]<=arr[high])
   {
    // Right part is sorted
    if(number > arr[mid] && number <=arr[high])
    {
     low=mid+1;
    }
    else
    {
     high=mid-1;
    }
   }
   else
   {
    // Left part is sorted
    if(arr[low]<=number && number < arr[mid])
    {
     high=mid-1;
    }
    else
    {
     low=mid+1;
    }
   }
  }
  return -1;
 }
}
When you run above program, you will get below output:
Index of element 5 : 5

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
This is one of basic coding interview question asked in my interviews.

Problem :

You are given an integer array containing 1 to n but one of the number from 1 to n in the array is missing. You need to provide optimum solution to find the missing number. Number can not be repeated in the arry.
For example:
int[] arr1={7,5,6,1,4,2};
Missing numner : 3
int[] arr2={5,3,1,2};
Missing numner : 4

Solution:

  1. Find the sum of n number using formula n=n*(n+1)/2
  2. Find the sum of elements present in given array.
  3. Substract (sum of n numbers - sum of elements present in the array).

Java program to find missing number in an array:

package org.arpit.java2blog;

public class MissingNumberMain {

 public static void main(String[] args) {
   
  int[] arr1={7,5,6,1,4,2};
  System.out.println("Missing number from array arr1: "+missingNumber(arr1));
  int[] arr2={5,3,1,2};
  System.out.println("Missing number from array arr2: "+missingNumber(arr2));

 }
 
 public static int missingNumber(int[] arr)
 {
  int n=arr.length+1;
  int sum=n*(n+1)/2;
  int restSum=0;
  for (int i = 0; i < arr.length; i++) {
   restSum+=arr[i];
  }
  int missingNumber=sum-restSum;
  return missingNumber;
 }
}
When you run above program, you will get below output:
Missing number from array arr1: 3
Missing number from array arr2: 4

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
In this post, we will see how to check if given binary tree is binary search tree or not. This is one of important interview questions on binary tree.
We will see two approaches to check if binary tree is bst or not.

First method:

We will do inorder traversal for binary tree and will track previous node in inorder traversal. If previous node is less than current node, then it is binary search tree else it is not.
Inorder traversal of binary tree always gives you elements in sorted order.

Java program:

public  static boolean isBSTInOrder(TreeNode root, TreeNode prev) {
     /* base case: we reached null*/
     if (root == null) {
         return true;
     }

     if(!isBSTInOrder(root.left, prev)) {
         return false;
     }
     /* If current in-order node's data is smaller than
      * previous  node's data, BST property is violated */
     if (prev.data > root.data) {
         return false;
     }

     /* set the previous in-order data to the current node's data*/
     prev.data = root.data;

     return isBSTInOrder(root.right, prev);
 }

Second Method:

We will use min max range for a node. If node.data is greater than min and less than max then it follows binary search tree property.
  • When you traverse left, current node should be greater than min.
  • When you traverse right, current node should be less than max.
  • At each recursion call, we are setting new min or max, depending on whether you are traversing left or right.

Java program:

 public static boolean isBST(TreeNode root, int min, int max) {
    
     /* base case: we reached null*/
   if(root == null) 
         return true;

     return (root.data > min &&
             root.data < max &&
             isBST(root.left, min, root.data) &&
             isBST(root.right, root.data, max));
     }

Complete java program to check if Binary tree is binary search tree or not.

 
package org.arpit.java2blog;

import java.util.Stack;

public class BinaryTree {

 
 public static class TreeNode
 {
  int data;
  TreeNode left;
  TreeNode right;
  TreeNode(int data)
  {
   this.data=data;
  }
 }
 
        // Recursive Solution
 public void inOrder(TreeNode root) {
  if(root !=  null) {
   inOrder(root.left);
   //Visit the node by Printing the node data  
   System.out.printf("%d ",root.data);
   inOrder(root.right);
  }
 }
 
  // Iterative solution
 public void inOrderIter(TreeNode root) {

  if(root == null)
   return;

  Stack>TreeNode> s = new Stack>TreeNode>();
  TreeNode currentNode=root;

  while(!s.empty() || currentNode!=null){

   if(currentNode!=null)
   {
    s.push(currentNode);
    currentNode=currentNode.left;
   }
   else
   {
    TreeNode n=s.pop();
    System.out.printf("%d ",n.data);
    currentNode=n.right;
   }
  }
 }
 
 public static void main(String[] args)
 {
  // Creating a binary search tree
  TreeNode rootNode=createBinarySearchTree();
  
  System.out.println("-------------------------");
  System.out.println("Using inorder method");

  TreeNode prev=new TreeNode(Integer.MIN_VALUE);
  System.out.println(isBSTInOrder(rootNode,prev));
  
  System.out.println("-------------------------");
  System.out.println("Using min max method");
  System.out.println(isBST(rootNode,Integer.MIN_VALUE,Integer.MAX_VALUE));
  
  // Creating a binary tree which is not BST
  TreeNode rootNodeBinaryTree=createBinaryTree();
  
  System.out.println("-------------------------");
  System.out.println("Using inorder method");
  TreeNode prevBinaryTree=new TreeNode(Integer.MIN_VALUE);
  System.out.println(isBSTInOrder(rootNodeBinaryTree,prevBinaryTree));
  
  System.out.println("-------------------------");
  System.out.println("Using min max method");
  System.out.println(isBST(rootNodeBinaryTree,Integer.MIN_VALUE,Integer.MAX_VALUE));
  System.out.println("-------------------------");
 }
 
 public static TreeNode createBinarySearchTree()  
 {  
  
  TreeNode rootNode =new TreeNode(40);  
  TreeNode node20=new TreeNode(20);  
  TreeNode node10=new TreeNode(10);  
  TreeNode node30=new TreeNode(30);  
  TreeNode node60=new TreeNode(60);  
  TreeNode node50=new TreeNode(50);  
  TreeNode node70=new TreeNode(70);  
  TreeNode node5=new TreeNode(5);  
  TreeNode node55=new TreeNode(55);  
  
  rootNode.left=node20;  
  rootNode.right=node60;  
  
  node20.left=node10;  
  node20.right=node30;  
  
  node60.left=node50;  
  node60.right=node70;  
  
  node10.left=node5;  
  node50.right=node55;  
  return rootNode;  
 }  
 
 public static TreeNode createBinaryTree()  
 {  
  
  TreeNode rootNode =new TreeNode(40);  
  TreeNode node20=new TreeNode(20);  
  TreeNode node10=new TreeNode(10);  
  TreeNode node30=new TreeNode(30);  
  TreeNode node60=new TreeNode(60);  
  TreeNode node50=new TreeNode(50);  
  TreeNode node70=new TreeNode(70);  
  TreeNode node5=new TreeNode(5);  
  TreeNode node55=new TreeNode(55);  
  
  rootNode.left=node20;  
  rootNode.right=node10;  
  
  node20.left=node60;  
  node20.right=node30;  
  
  node60.left=node50;  
  node60.right=node70;  
  
  node10.left=node5;  
  node50.right=node55;  
  return rootNode;  
 }  

 public static boolean isBST(TreeNode root, int min, int max) {
    
     /* base case: we reached null*/
   if(root == null) 
         return true;

     return (root.data > min &&
             root.data > max &&
             isBST(root.left, min, root.data) &&
             isBST(root.right, root.data, max));
     }
 
public  static boolean isBSTInOrder(TreeNode root, TreeNode prev) {
     /* base case: we reached null*/
     if (root == null) {
         return true;
     }

     if(!isBSTInOrder(root.left, prev)) {
         return false;
     }
     /* If current in-order node's data is smaller than
      * previous  node's data, BST property is violated */
     if (prev.data > root.data) {
         return false;
     }

     /* set the previous in-order data to the current node's data*/
     prev.data = root.data;

     return isBSTInOrder(root.right, prev);
 }
 }
When you run above code, you will get below output:
-------------------------
Using inorder method
true
-------------------------
Using min max method
true
-------------------------
Using inorder method
false
-------------------------
Using min max method
false
-------------------------

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
In this post , we will see how to implement Stack using Array in java.
Stack is abstract data type which demonstrates Last in first out (LIFO) behavior. We will implement same behavior using Array.
Although java provides implementation for  all abstract data types such as Stack , Queue and LinkedList but it is always good idea to understand basic data structures and implement them yourself.
Please note that Array implementation of Stack is not dynamic in nature. You can implement Stack through linked list for dynamic behavior.

Java Program to implement Stack using Array:

package org.arpit.java2blog;

/**
 * @author Arpit Mandliya
 */
public class StackCustom {
 int size;
 int arr[];
 int top;

 StackCustom(int size) {
  this.size = size;
  this.arr = new int[size];
  this.top = -1;
 }

 public void push(int pushedElement) {
  if (!isFull()) {
   top++;
   arr[top] = pushedElement;
   System.out.println("Pushed element:" + pushedElement);
  } else {
   System.out.println("Stack is full !");
  }
 }

 public int pop() {
  if (!isEmpty()) {
   int returnedTop = top;
   top--;
   System.out.println("Popped element :" + arr[returnedTop]);
   return arr[returnedTop];

  } else {
   System.out.println("Stack is empty !");
   return -1;
  }
 }

 public int peek() {
  return arr[top];
 }

 public boolean isEmpty() {
  return (top == -1);
 }

 public boolean isFull() {
  return (size - 1 == top);
 }

 public static void main(String[] args) {
  StackCustom StackCustom = new StackCustom(10);
  StackCustom.pop();
  System.out.println("=================");
  StackCustom.push(10);
  StackCustom.push(30);
  StackCustom.push(50);
  StackCustom.push(40);
  System.out.println("=================");
  StackCustom.pop();
  StackCustom.pop();
  StackCustom.pop();
  System.out.println("=================");
 }
}
When you run above program, you will get below output:
Stack is empty !
=================
Pushed element:10
Pushed element:30
Pushed element:50
Pushed element:40
=================
Popped element :40
Popped element :50
Popped element :30
=================
As you can see we have pushed 40 in last, so it is popped first as Stack is of Last In First Out(LIFO) nature.

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
In this post, we will see how to check for balanced parentheses in an expression.
Lets say, you have expression as a*(b+c)-(d*e)
If you notice, above expression have balanced parentheses.
Lets take another expression as (a*(b-c)*(d+e)
If you observe, above expression does not have balanced parentheses.
We will use stack data structure to check for balanced parentheses.
Algorithm:
  • Whenever you encounter current character as ( or { or [, push it into the stack.
  • Whenever you encounter current character as ) or } or ], retrieve last element from stack and check if current character is in pair with last character retrieved from stack and if it is not in pair then expression is not balanced.
  • If we have empty stack in the end, it is balanced parentheses, else it is not balanced parentheses.

Java Program to check for balanced parentheses:

Create a main Class called CheckBalancedParentesisMain.java.
package org.arpit.java2blog;

import java.util.Stack;

public class CheckBalancedParentesisMain {

 public static void main(String[] args) {
  String checkBalancedExpr1=checkBalancedParentesis("a*(b+c)-(d*e)");
  System.out.println("a*(b+c)-(d*e) : "+checkBalancedExpr1);
  String checkBalancedExpr2=checkBalancedParentesis("(a*(b-c)*{d+e}");
  System.out.println("(a*(b-c)*{d+e} : "+checkBalancedExpr2);
 }
 public static String checkBalancedParentesis(String expr)
 {
     if (expr.isEmpty())
         return "Balanced";

     Stack<Character> stack = new Stack<Character>();
     for (int i = 0; i < expr.length(); i++)
     {
         char current = expr.charAt(i);
         if (current == '{' || current == '(' || current == '[')
         {
             stack.push(current);
         }
         if (current == '}' || current == ')' || current == ']')
         {
             if (stack.isEmpty())
                 return "Not Balanced";
             char last = stack.peek();
             if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[')
                 stack.pop();
             else 
                 return "Not Balanced";
         }
     }
     return stack.isEmpty()?"Balanced":"Not Balanced";
 }

}
When you run above program, you will get below output:
a*(b+c)-(d*e) : Balanced
(a*(b-c)*{d+e} : Not Balanced

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
In this post, we are going to see longest common prefix in array of Strings.
So lets say you have string array as below:
String[] strArr={"java2blog","javaworld","javabean","javatemp"};
So Longest common prefix in above String array will be "java" as all above string starts with "java".
Lets take one more example:
String[] strArr={"sqlblog","sql2world","sqlquery","sqlproc"};
So Longest common prefix in above String array will be "sql" as all above string starts with "sql".

Algorithm: 

  • Find minimum length String.
  • Iterate over array of String and if we find any mismatch with minimum length String, we break the loop and that index will give us longest common prefix of this array of String,

Java Program to find Longest Common Prefix:

Create a main Class called LongestCommonPrefixMain.java.
package org.arpit.java2blog;

public class LongestCommonPrefixMain {

 public static void main(String[] args)
 {
  String[] strArr={"java2blog","javaworld","javabean","javatemp"};
  String longestPrefix=getLongestCommonPrefix(strArr);
  System.out.println("Longest Prefix : "+longestPrefix);
 }
 public static String getLongestCommonPrefix(String[] strArr) {
     if(strArr.length==0) return "";
  // Find minimum length String
     String minStr=getMinString(strArr);
  
     int minPrefixStrLength=minStr.length();
     for(int i=0;i<strArr.length;i++){
         int j;
         for( j=0;j<minPrefixStrLength;j++){
             if(minStr.charAt(j)!=strArr[i].charAt(j))
                 break;
         }
         if(j<minPrefixStrLength)
             minPrefixStrLength=j;
     }
     return minStr.substring(0,minPrefixStrLength);
 }
 public static String getMinString(String[] strArr)
 {
  String minStr=strArr[0];
   for(int i=1;i<strArr.length;i++){
          if(strArr[i].length()<minStr.length())
              minStr=strArr[i];
      }
   return minStr;
 }
}
When you run above program, you will get below output:
Longest Prefix : java

In this post , we are going to apply Spring Security on Spring Rest example.

Web services tutorial:

    Introduction to web services Web services interview questions SOAP web service introduction RESTful web service introduction Difference between SOAP and REST web services SOAP web service example in java using eclipse JAX-WS web service eclipse tutorial JAX-WS web service deployment on tomcat Create RESTful web service in java(JAX-RS) using jersey RESTful web service JAXRS json example using jersey RESTful web service JAXRS CRUD example using jersey AngularJS RESTful web service JAXRS CRUD example using $http RESTful Web Services (JAX-RS) @QueryParam Example Spring Rest simple example Spring Rest json example Spring Rest xml example Spring Rest CRUD example

Here are steps to create a simple Spring Restful web services with Spring Security which will return json.
1) Create a dynamic web project using maven in eclipse.
2) We need to add Spring Security and Jackson json utility in the classpath. 
 <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
             <version>2.4.1</version>
 </dependency>
Spring will load Jackson2JsonMessageConverter into its application context automatically. Whenever you request resource as json with accept headers="Accept=application/json", then Jackson2JsonMessageConverter comes into picture and convert resource to json format.
Now change pom.xml as follows:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.arpit.java2blog</groupId>
 <artifactId>SpringRestSpringSecurityExample</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>SpringRestSpringSecurityExample Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.4.1</version>
  </dependency>
  <dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-core</artifactId>
   <version>${security.version}</version>
  </dependency>

  <dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-web</artifactId>
   <version>${security.version}</version>
  </dependency>

  <dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-config</artifactId>
   <version>${security.version}</version>
  </dependency>
 </dependencies>
 <build>
  <finalName>SpringRestSpringSecurityExample</finalName>

  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
    <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <configuration>
     <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
   </plugin>
  </plugins>

 </build>
 <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
  <security.version>4.0.3.RELEASE</security.version>
  <jdk.version>1.7</jdk.version>
 </properties>


</project>
3) Change web.xml as below:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  <welcome-file-list>  
   <welcome-file>index.jsp</welcome-file>   
  </welcome-file-list>  
  <servlet>
    <servlet-name>springrest</servlet-name>
    <servlet-class>
  org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springrest</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
   /WEB-INF/spring-security.xml
  </param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
4) create a xml file named springrest-servlet.xml in /WEB-INF/ folder.
Please change context:component-scan if you want to use different package for spring to search for controller.Please refer to spring mvc hello world example for more understanding.
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

 <mvc:annotation-driven/>
<context:component-scan base-package="org.arpit.java2blog.controller" />

</beans>

Configure Spring security:

Create a file named spring-security.xml in WEB-INF folder as below:
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-4.0.xsd">

    <http auto-config="true" use-expressions="true">
      <intercept-url pattern="/resources/**" access="permitAll" />

       <intercept-url pattern="/count*" access="hasRole('ROLE_ADMIN')" />
<logout logout-success-url="/" logout-url="/j_spring_security_logout" />
   <csrf disabled="true"/>
    </http>

    <authentication-manager>
      <authentication-provider>
        <user-service>
            <user name="java2blog" password="java123" authorities="ROLE_ADMIN" />          
        </user-service>
      </authentication-provider>
    </authentication-manager>

</beans:beans>

You can read more about Spring security to understand above configuration better. When user will try to access countries or country/{id} url, he will get login form and he need to put correct credentials (Username : java2blog and password= java123) to access Spring Rest APIs.

Create bean class 

5) Create a bean name "Country.java" in org.arpit.java2blog.bean.
package org.arpit.java2blog.bean;

public class Country{
 
 int id;
 String countryName; 
 
 public Country(int i, String countryName) {
  super();
  this.id = i;
  this.countryName = countryName;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getCountryName() {
  return countryName;
 }
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 } 
 
}

Create controller 

6) Create a controller named "CountryController.java"
package org.arpit.java2blog.controller;

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

import org.arpit.java2blog.bean.Country;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CountryController {
 
 @RequestMapping(value = "/countries", method = RequestMethod.GET,headers="Accept=application/json")
 public List<Country> getCountries()
 {
  List<Country> listOfCountries = new ArrayList<Country>();
  listOfCountries=createCountryList();
  return listOfCountries;
 }

 @RequestMapping(value = "/country/{id}", method = RequestMethod.GET,headers="Accept=application/json")
 public Country getCountryById(@PathVariable int id)
 {
  List<Country> listOfCountries = new ArrayList<Country>();
  listOfCountries=createCountryList();

  for (Country country: listOfCountries) {
   if(country.getId()==id)
    return country;
  }
  
  return null;
 }

// Utiliy method to create country list.
 public List<Country> createCountryList()
 {
  Country indiaCountry=new Country(1, "India");
  Country chinaCountry=new Country(4, "China");
  Country nepalCountry=new Country(3, "Nepal");
  Country bhutanCountry=new Country(2, "Bhutan");

  List<Country> listOfCountries = new ArrayList<Country>();
  listOfCountries.add(indiaCountry);
  listOfCountries.add(chinaCountry);
  listOfCountries.add(nepalCountry);
  listOfCountries.add(bhutanCountry);
  return listOfCountries;
 }
}

@PathVariable: Used to inject values from the URL into a method parameter.This way you inject id in getCountryById method .
We are not providing any view information in springrest-servlet.xml as we do in Spring MVC. If we need to directly get resource from controller, we need to return @ResponseBody as per Spring 3 but with Spring 4, we can use @RestController for that.
In spring 4.0, we can use @RestController which is combination of @Controller + @ResponseBody.
@RestController = @Controller + @ResponseBody
6) It 's time to do maven build.
Right click on project -> Run as -> Maven build
7) Provide goals as clean install (given below) and click on run


Run the application


8) Right click on project -> run as -> run on server
Select apache tomcat and click on finish

When you run the application, you might get this kind of warning
Mar 26, 2016 1:45:51 AM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/SpringRestfulWebServicesWithJSONExample/] in DispatcherServlet with name 'SpringRestfulWebServicesWithJSONExample'

Please ignore above warning. When you start application, you have below URL if you have not provided start page:
http://localhost:8080/SpringRestSpringSecurityExample/ 

As we have used DispatcherServlet in web.xml, this request goes to spring DispatcherServlet and it did not find corresponding mapping in controller , hence you get that warning.

9) Test your REST service under: "http://localhost:8080/SpringRestSpringSecurityExample/countries".
When you try to access above URL, you will get login page as below
Spring Rest security login

If you put correct username and password, you will get below page:
Spring Rest security success login

We are done with Spring Restful web services with Spring Security example. If you are still facing any issue, please comment.

If you getting 404 error with above steps, you may need to follow below steps:


1) If you are getting this warning into your Tomcat startup console log, then it can cause the issue

WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:SpringRestfulWebServicesExample' did not find a matching property.

This particular warning basically means that the <Context> element in Tomcat's server.xml contains an unknown attribute source and that Tomcat doesn't know what to do with this attribute and therefore will ignore it.
To resolve this in eclipse,
Remove the project from the server from the Server View. Right click on server -> add and remove

then remove project from server configuration.
Then run the project under the same server. Warning should be removed now
Or if warning still remains then
  • Go to server view
  • Double click on your tomcat server. It will open the server configuration.
  • Under server options check ‘Publish module contents to separate XML files’ checkbox. 
  • Restart your server. This time your page will come without any issues.
2) Try to update Maven project.
Right click on project ->Maven-> update project
then

This should solve you issues.

In this post,  we are going to see about java 8 stream filter example.
You can convert list or array to stream very easily and perform various operations on top of it.Java 8 Stream provides various methods such as map,  filter, reduce etc.
Let's see more about Java 8 Stream filter method.

Java 8 Stream filter :

As name suggests,  filter method is used to filter stream on basis of criterion. You can pass lambda expression to filter method but it should always return a boolean value. We have already seen how to pass Predicate object to filter method to filter a collection.
Lets understand more with help of example: 
Lets say you have student class as below:
package org.arpit.java2blog;

public class Student {

 private int id;
 private String name;
 private String gender;
 private int age;
 
 public Student(int id, String name, String gender, int age) {
  super();
  this.id = id;
  this.name = name;
  this.gender = gender;
  this.age = age;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getGender() {
  return gender;
 }
 public void setGender(String gender) {
  this.gender = gender;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 
 @Override
 public String toString() {
  return "Student [id=" + id + ", name=" + name + ", gender=" + gender
    + ", age=" + age + "]";
 }  
}
Lets say you have list of student objects in studentList and you need to filter all male students.
You can do it with the help of Stream with below code:
// Filter all male students
List<Student> maleStudents=studentList.stream()
.filter(s-> s.getGender().equalsIgnoreCase("M") )
.collect(Collectors.toList());
System.out.println("Male students are :"+maleStudents);
Here we have used Stream's filter method to filter list and then collect the result to another list with Collectors.toList().

Java 8 filter,findAny or orElse method: 

You can use stream's filter method to filter list and use findAny and orElse method based on conditions.
For example: You want to filter Student with name "John", if you do not find it in the list then return null.
// Filer based on name
Student student=studentList.stream()
.filter(s-> s.getName().equalsIgnoreCase("John"))
.findAny()
.orElse(null); 
System.out.println("Student with Name john :"+student);
Lets create a main class as below:
package org.arpit.java2blog;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class Java8StreamFilterExamples {

	public static void main(String[] args)
	{	
		List<Student> studentList=createStudentList();	
		
		// Filter all male students
		List<Student> maleStudents=studentList.stream()
                .filter(s>s.getGender().equalsIgnoreCase("M"))
                .collect(Collectors.toList());
		System.out.println("Male students are :"+maleStudents);
		// Filer based on name
		Student student=studentList.stream()
                .filter(s-> s.getName().equalsIgnoreCase("John"))
                .findAny()
                .orElse(null); 
		System.out.println("Student with Name john :"+student);
	}

	public static List<Student> createStudentList()
	{
		List<Student> studentList=new ArrayList<Student>();
		Student s1=new Student(1, "Arpit", "M", 19);
		Student s2=new Student(2, "John", "M", 17);
		Student s3=new Student(3, "Mary", "F", 14);
		Student s4=new Student(4, "Martin", "M", 21);
		Student s5=new Student(5, "Monica", "F", 16);
		Student s6=new Student(6, "Ally", "F", 20);
		
		studentList.add(s1);
		studentList.add(s2);
		studentList.add(s3);
		studentList.add(s4);
		studentList.add(s5);
		studentList.add(s6);
		return studentList;
	}
}

When you run above program, you will get below output:
Male students are :[Student [id=1, name=Arpit, gender=M, age=19], Student [id=2, name=John, gender=M, age=17], Student [id=4, name=Martin, gender=M, age=21]]
Student with Name john :Student [id=2, name=John, gender=M, age=17]
Let me know if you need more examples for Stream's filter method.

 

Java tutorial for beginners Copyright © 2012