Other queue implementation in java

               A basic queue is a collection of elements with a front end and rear end. Some of the other types of queue’s are listed below.

PriorityQueue: A queue with priority value associated with it. It dequeued according to the priority. Generally, higher priority is dequeued first.

ArrayDeque : This implementation of queue can be resizable. The elements can be added or removed at both front and back ends.

The java implementations of both queues are given below.

1.Priority Queue implementation in java:

              This program uses the built in packages java.util.PriorityQueue and java.util.Queue.

Steps:

  • ·       Develop a class with main() function.
  • ·       Create an object for Queue class.
  • ·       Insert the data elements to the queue by add() function.
  • ·       Deque the elements until the last element and print the queue elements.

Program:

import java.util.PriorityQueue;

import java.util.Queue;

public class PriorityQueueEg {

    public static void main(String[] args) {

        Queue<Integer> priorityQueue1 = new PriorityQueue<>();

        // Enqueue elements

        priorityQueue1.add(310);

        priorityQueue1.add(130);

        priorityQueue1.add(253);

        priorityQueue1.add(454);

        priorityQueue1.add(364);

        // printing the queue elements

        System.out.println("The elements in the PriorityQueue is: " + priorityQueue1);

         // deleting the elements until the queue is empty(Deque)

        while (!priorityQueue1.isEmpty()) {

            System.out.println("The Removed element is: " + priorityQueue1.poll());

        }

    }

}

Output:

C:\raji\blog>javac PriorityQueueEg.java

C:\raji\blog>java PriorityQueueEg

The elements in the PriorityQueue is: [130, 310, 253, 454, 364]

The Removed element is: 130

The Removed element is: 253

The Removed element is: 310

The Removed element is: 364

The Removed element is: 454

Next implementation is given as follows.

ArrayDeque implementation in java:

              This implementation uses the built in packages java.util.ArrayDeque and java.util.Deque.

Steps:

  • ·       write a class with main() function.
  • ·        Queue class object is created as integer.
  • ·       Enque(insert) the data elements to the queue by add() function.
  • ·       Delete the elements until the last element and print the queue elements.

Program:

import java.util.ArrayDeque;

import java.util.Deque;

public class ArrayDequeEg {

    public static void main(String[] args) {

        Deque<Integer> deque1 = new ArrayDeque<>();

        // Enqueue(adding) elements at the end

        deque1.addLast(231);

        deque1.addLast(551);

        deque1.addLast(300);

        deque1.addLast(677);    

        // The elements in deque is displayed here

        System.out.println("ArrayDeque: " + deque1);

        // Dequeue(remove) the  elements from the front

        while (!deque1.isEmpty()) {

            System.out.println("Removed element: " + deque1.pollFirst());

        }

    }

}

Output:

C:\raji\blog>javac ArrayDequeEg.java

C:\raji\blog>java ArrayDequeEg

ArrayDeque: [231, 551, 300, 677]

Removed element: 231

Removed element: 551

Removed element: 300

Removed element: 677

These are the other queue implementation in java. Keep coding!!!

Simple Queue implementation in java

    Queue is a collection of elements stored in sequential manner. It has a principle called FIFO (First In First Out). It means the element added in the queue is removed first.The implementation of queue is done easily using java.

The built-in packages in java for implementing queue is given below.

java.util.LinkedList

java.util.Queue

The implementation of simple queue is as follows.

It has 5 basic operations.

Enqueue : It adds the element to the queue.

Dequeue: It removes the element from the queue.

Size : It finds the size of the queue.

isEmpty: It checks the queue has elements or not.

peek() : It finds the front elements.

Steps to implement the program:

First, include the built-in packages.

Create the class  QueueSimple with main () function.

An object is created from builtin class “Queue” as integer.

Add the elements to the queue by using add() function.

Print the elements in the queue.

Using the peek () function to print the front element.

Pool() function is used to delete the element from the queue. This operation is called “Dequeue”.

To check the queue is empty or not, isEmpty() function is used.

Size() function is used to check the size of the queue.

Java code:

import java.util.LinkedList;

import java.util.Queue;

public class QueueSimple {

    public static void main(String[] args) {

        // let us create a queue

        Queue<Integer> queue1 = new LinkedList<>();

        // Insert elements to the queue(Enqueue)

        queue1.add(34);

        queue1.add(45);

        queue1.add(56);

        queue1.add(75);

        queue1.add(89);

        // Print the elements in the queue

        System.out.println("The elements in the Queue are: " + queue1);

        //Get the front element(Peek) and print it

        int front = queue1.peek();

        System.out.println("Front element of the queue is: " + front);

        // Remove elements(Dequeue) from the queue

        int del = queue1.poll();

        System.out.println("Deleted element: " + del);

        // print the queue elements after deleting (dequeuing) an element

        System.out.println("Queue after deletion: " + queue1);

        // Check whether the queue has no elements

        boolean isEmpty = queue1.isEmpty();

        if(isEmpty)

          System.out.println("The queue is empty");

        else

          System.out.println("The queue is not empty");

        // Find the size of the queue

        int size = queue1.size();

        System.out.println("Size of the queue is: " + size);

    }

}

Output:

C:\raji\blog>javac QueueSimple.java

C:\raji\blog>java QueueSimple

The elements in the Queue are: [34, 45, 56, 75, 89]

Front element of the queue is: 34

Deleted element: 34

Queue after deletion: [45, 56, 75, 89]

The queue is not empty

Size of the queue is: 4

This is the way of implementing  simple queue in java. If you have any queries, just drop a comment below.

Keep coding!!!

Java implementation of trapping the rainwater using stack

 Trapping the Rainwater is a classical algorithmic problem. It finds the trapping water on the elevation map. Here, the elevation map is implemented by an array as stack.

Let us implement this algorithm in Java.

  1. First, create an integer array for storing the stack. Each element represents a bar in the elevation map. The bar represents the count of trapping water after the rain.
  2. Initialize the two pointers. One points to the left side, and another points to the right side of the array.
  3. Find the maximum height of the right and left side of the array and store it in two variables.
  4. Finally, calculate the trapped water value by moving the pointers towards the center. It’s time to find the maximum and minimum values from the left and right.

Java Implementation

public class TrapitRainWater {

    public static int trapit(int[] h) {

        if (h == null || h.length == 0) {

            return 0;

        }

        int Tleft = 0, Tright = h.length - 1;

        int TleftMax = 0, TrightMax = 0;

        int trappedvalue = 0;

        while (Tleft < Tright) {

            if (h[Tleft] < h[Tright]) {

                if (h[Tleft] >= TleftMax) {

                    TleftMax = h[Tleft];

                } else {

                    trappedvalue += TleftMax - h[Tleft];

                }

                Tleft++;

            } else {

                if (h[Tright] >= TrightMax) {

                    TrightMax = h[Tright];

                } else {

                    trappedvalue += TrightMax - h[Tright];

                }

                Tright--;

            }

        }

        return trappedvalue;

    }

    public static void main(String[] args) {

        int[] h = {1, 0, 2, 3, 4, 1, 0, 3, 1, 0, 3, 2};

        int finalvalue = trapit(h);

        System.out.println("The count of the trapped water is: " + finalvalue);

    }

}

Output:

C:\raji\blog>javac TrapitRainWater.java

C:\raji\blog>java TrapitRainWater

The count of the trapped water is: 11

This is the way of implementing trapping the rain water using stack in Java. Keep coding!!!

If you need any more help with this algorithm or others, feel free to ask!

Largest Rectangle in histogram using java

              It is a classic problem in histogram which finds the largest rectangle. The histogram has a collection of integers represented by an array. Each element denotes the height of the bar.

Here, a stack is used to implement the largest rectangle in histogram.

Let us implement the largest rectangle in histogram.

  • ·       First, create a integer stack for storing the histogram.
  • ·       Declare an integer variable maxiArea and n.
  • ·       Iterate the stack for finding the largest bar in the histogram.
  • ·       If the current bar is greater than the bar in the top of the stack, insert the current value to the stack.
  • ·       Else the value is popped. Check until the last element.
  • ·       Calculate the largest area of the value and display it.

Program:

import java.util.Stack;

public class LargestRectangleHistogram1 {

    public static int largestRectArea(int[] hts) {

        Stack<Integer> stack1 = new Stack<>();

        int maxiArea = 0;

        int n = hts.length;

        for (int i = 0; i < n; i++) {

            while (!stack1.isEmpty() && hts[i] < hts[stack1.peek()]) {

                int ht = hts[stack1.pop()];

                int wth = stack1.isEmpty() ? i : i - stack1.peek() - 1;

                maxiArea = Math.max(maxiArea, ht * wth);

            }

            stack1.push(i);

        }

        while (!stack1.isEmpty()) {

            int ht = hts[stack1.pop()];

            int wth = stack1.isEmpty() ? n : n - stack1.peek() - 1;

            maxiArea = Math.max(maxiArea, ht * wth);

        }

         return maxiArea;

    }

    public static void main(String[] args) {

        int[] hts = {23, 10, 15,46, 72, 50};

        int maxiArea = largestRectArea(hts);

        System.out.println("The area of Largest Rectangle is: " + maxiArea);

    }

}

While executing this program,you will get the below output.

C:\raji\blog>javac LargestRectangleHistogram1.java

C:\raji\blog>java LargestRectangleHistogram1

The area of Largest Rectangle is: 138

That’s all. This is the way of implementing largest rectangle in histogram. Keep coding!!!!

Valid parenthesis checking using Stack in java

     Let us solve a common problem called “Valid parentheses”. It is a problem which checks a given string has a valid parenthesis. It means that the parentheses are nested and closed properly. If you use stack for solving this problem, it is good to be effective.

List of parentheses:

‘(‘ , ’)’ , ’[‘ , ’]’ , ’{‘ , ’}’.

Valid usage of parentheses:

  • ‘({[]})’
  • ‘{[()]}’
  • ‘[{()}]’

Let us implement this program in java.

Program:

  • ·       Create a stack for finding the opening parenthese.
  • ·       Traverse the string character by character.
  • ·       Check for opening parenthesis, if occurs,insert(push) the parenthese into stack.
  • ·       If it is a closing parenthesis, check the stack is having its opening parenthesis.
  • ·       If these two are matching, pop the element from the stack. Otherwise,print the string is invalid.
  • ·       Repeat this until the stack become empty.

Here is the program.

import java.util.Stack;

public class ValidParenthesesStackEg {

    public static boolean isValidorNot(String s) {

        Stack<Character> stack1 = new Stack<>();

 

        for (char c : s.toCharArray()) {

            if (c == '(' || c == '{' || c == '[') {

                stack1.push(c);

            } else if (c == ')' || c == '}' || c == ']') {

                if (stack1.isEmpty()) {

                    return false;

                }

                char top = stack1.pop();

                if ((c == ')' && top != '(') ||

                    (c == '}' && top != '{') ||

                    (c == ']' && top != '[')) {

                    return false;

                }

            }

        }

 

        return stack1.isEmpty();

    }

     public static void main(String[] args) {

        String test1 = "({[]})";

        String test2 = "[{()}]";

        String test3 = "{([";

        if(isValidorNot(test1))

        System.out.println(test1 + " is valid");

        else

          System.out.println(test1 + " is invalid");

        if(isValidorNot(test2))

        System.out.println(test2 + " is valid");

        else

          System.out.println(test2 + " is invalid");

       if(isValidorNot(test3))

        System.out.println(test3 + " is valid");

        else

          System.out.println(test3 + " is invalid");

    }

}

Output:

C:\raji\blog>javac ValidParenthesesStackEg.java

C:\raji\blog>java ValidParenthesesStackEg

({[]}) is valid

[{()}] is valid

{([ is invalid

Using the above implementation, it is efficient to find the string is having valid parenthesis. Keep Coding!!

How to find the Next Greater element in java?

               An array of integers is given. You have to find the next greater element for each element in the array.  This is one of the interview question in java.

Let us find the solution for this problem.

  • ·       First, write a class with main function. next, declare an array with some ‘no’ of elements.
  • ·       Create a stack with new object “stack1”.
  • ·       Check the current element of the array with other elements for greater value. If the value is less, then delete the elements. 
  • ·       If the value is greater than the current element, push the current element to stack. otherwise, insert -1 value to stack.
  • ·       Finally, print the value. If stack is null, then there is no greater number.

Program:

import java.util.Stack;

public class NextGElement {

    public static int[] nextGElements(int[] arr) {

        int no = arr.length;

        int[] result1 = new int[no];

        Stack<Integer> stack1 = new Stack<>();

        for (int i = no - 1; i >= 0; i--) {

            // delete the elements which are less than or equal to the current element

            while (!stack1.isEmpty() && stack1.peek() <= arr[i]) {

                stack1.pop();

            }

            // If stack is null, there is no bigger number

            result1[i] = stack1.isEmpty() ? -1 : stack1.peek();

            // insert the current element to the stack

            stack1.push(arr[i]);

        }

        return result1;

    }

    public static void main(String[] args) {

        int[] arr1 = {234, 345, 20,530,56};

        int[] result1 = nextGElements(arr1);

         // let us display the output

        System.out.print("The Next Greater Elements are: ");

        for (int value : result1) {

            System.out.print(value + " ");

        }

    }

}

Compile and run the program to get the output.

Here, is the output.

C:\raji\blog>javac NextGElement.java

C:\raji\blog>java NextGElement

The Next Greater Elements are: 345 530 530 -1 -1

Using the above logic, it is easy to implement the next greater element problem in java. Happy coding!!!

The Stock Span Problem in java

    Stocks are everywhere today. This problem deals with stock span calculation for all days. To calculate this, check the stock prices for consecutive days before the day given to you. The logic is to check the stock price on current day with the price on the given day.

This problem can be implemented in java as follows.

  • ·       First,use the builtin Stack package.
  • ·       Write a public class spanStockCalc with main() function.
  • ·       Include a function spanCalculate() with an argument sprices as integer.
  • ·       Find the length of the sprices and store it into variable ‘n’.
  • ·       Next,create a integer array with the size of n.
  • ·       A new object is created for stack.
  • ·       Using a for loop, check the two conditions. one is stackis empty or not , another one is check the stack elements with stack’s top elements.
  • ·       If these two conditions met, pop the element.
  • ·       Repeat the process.
  • ·       Finally, insert the element in stack.
  • ·       Inside the main function, assign values for array elements.
  • ·       Call the function and print the output.

Program:

import java.util.Stack;

public class spanStockCalc {

    // Function to calculate the stock span prices

    public static int[] spanCalculate(int[] sprices) {

        int n = sprices.length;

        int[] span = new int[n];

        Stack<Integer> stack1 = new Stack<>();

        for (int i = 0; i < n; i++) {

            // Calculation

            while (!stack1.isEmpty() && sprices[stack1.peek()] <= sprices[i]) {

                stack1.pop();

            }

            span[i] = (stack1.isEmpty()) ? (i + 1) : (i - stack1.peek());

            // insert the data

            stack1.push(i);

        }

        return span;

    }

    public static void main(String[] args) {

        int[] sprices = {450,30,70, 80, 90,175,120};

        int[] span = spanCalculate(sprices);

        // Final outcome

        System.out.print("Spans: ");

        for (int spans : span) {

            System.out.print(spans + " ");

        }

    }

}

Compile and run the program to get the output.

C:\raji\blog>javac spanStockCalc.java

C:\raji\blog>java spanStockCalc

Spans: 1 1 2 3 4 5 1

Note: Time complexity is O(n).

Stack implementation in java

               Stack is a basic data structure which store the data elements in such a way that LIFO.Stack class is included in java Collections.

The built-in package is: java.util.Stack.

Logic of stack:

  • LIFO (Last in First Out): The number which is inserted as last will be removed first.
  • Dynamic: The size of stack will be increased or decreased depends on the data.

Operations on Stack:

  • push(data) : it is used to add the elements to the stack.
  • pop() : It is used to delete a top most data.
  • peek() : This is used to view the top element of data.
  • search(): It finds a particular data in the stack.
  • empty() :It checks whether stack is empty or not.

Java Implementations on Stack Operations:

              This java program implements a stack and its operations. It has following steps.

Steps:

  • Include the built in java package.
  • A public class is created with main() function.
  • A new stack object is created. 5 elements are inserted into stack using push() function.
  • The stack elements are displayed using print() statement.
  •  peek() function is used to view the top elements without deleting.
  • Pop() function deletes the top element of the stack.
  • Search() method finds an element in the stack.
  • Empty() checks the stack is empty or not.

Program:

import java.util.Stack;

public class StackEg {

    public static void main(String[] args) {

     Stack<Integer> stackobj = new Stack<>();

        // inserting(Pushing) elements

        stackobj.push(100);

        stackobj.push(200);

        stackobj.push(300);

        stackobj.push(400);

        stackobj.push(500);

        // print the stack elements

        System.out.println("Stack : " + stackobj);

        // view the top element(Peek)

        int top1 = stackobj.peek();

        System.out.println("Top element: " + top1);

        // remove the top element in the stack(Pop)

        int popit = stackobj.pop();

        System.out.println("The element which is popped from the stack is: " + popit);

        // printing the stack elements after pop

        System.out.println("Stack after pop: " + stackobj);

        // finding an element

        int pos = stackobj.search(20);

        System.out.println("Position of element: " + pos);

        // finding the stack is empty or not.

        boolean isEmpty = stackobj.empty();

        System.out.println("stack empty " + isEmpty);

    }

}

Output:

C:\raji\blog>javac StackEg.java

C:\raji\blog>java StackEg

Stack : [100, 200, 300, 400, 500]

Top element: 500

The element which is popped from the stack is: 500

Stack after pop: [100, 200, 300, 400]

Position of element: -1

stack empty false

Note: Stack is useful when backtracking is needed and process the elements in last in first out order.

Josephus problem implementation in java

Finding a solution for a problem is always interesting. Here is the interesting problem called  “Josephus”.

What is the Josephus problem?

It is a classic game involves a eliminating a person from a group of people who stands in a circle. First, ‘n’ number of people in a circle. Count from a position. At the end of counting, eliminate the person. Continue the process until the person.

Java implementation of Josephus problem:

It can be done by two ways.

  • ·       Recursive function
  • ·       Iterative method

Implementation of Josephus problem using recursive function:

  •  It creates a class “Josephuspbm” with a main() function. A recursive function is created with two member variables.
  • ·       Check this ‘n’ value. If the n is equal to one, then return to 0. Otherwise, call the recursive function.
  • ·       Assign two integer variables with value. One is for total number of people and another one is step count.
  • ·       Call the recursive function and print the result.

Program:

public class JosephusPbm{

    // A recursive function to find the last person in the circle

    static int josephus(int n, int k) {

        if (n == 1) {

            return 0;  // one person is left

        } else {

            return (josephus(n - 1, k) + k) % n;

        }

    }

    public static void main(String[] args) {

        int n = 9;  // Total number of people

        int sc = 2;  // Step count

        int res = josephus(n, sc) + 1;

        System.out.println("The last person in the circle is: " + res);

    }

}

Compile and execute this program to get the output.

C:\raji\blog>javac JosephusPbm.java

C:\raji\blog>java JosephusPbm

The last person in the circle is: 3

Implementation of Josephus problem using Iterative function:

              Here, instead of a recursive function, it uses a for loop for iteration.

public class JosephusPbm1 {

    // iterative function

    static int josephusIterative(int n, int k) {

        int res = 0;

        for (int i = 1; i <= n; i++) {

            res = (res + k) % i;

        }

        return res;

    }

    public static void main(String[] args) {

        int n = 9;  // Total people

        int k = 2;  // Step count

        int res = josephusIterative(n, k) + 1;

        System.out.println("The last person in the circle is: " + res);

    }

}

The output is given below.

C:\raji\blog>javac JosephusPbm1.java

C:\raji\blog>java JosephusPbm1

The last person in the circle is: 3

This is the way of implementing Josephus problem in java. Enjoy coding!!!

Implementation of LinkedList in java

 Linkedlist is a type of data structure which has nodes and pointers. Node a structure which stores data and pointers are used to link the nodes. To implement linkedlist in Java collections framework, we use doubly-linked list.

Doubly-linkedlist has two pointers. One points to forward direction and another points to backward direction.

Use of doubly-linkedlist:

  • It is dynamic. You can increase the size at runtime.
  •  Insertions and deletions are done in efficient manner.

Implementation of Linked List:

              This includes the creation of a linked list, adding the elements, displaying the elements, removing a data and iteration.

Steps:

Include the builtin java packages java.util.LinkedList and java.util.Iterator.

 A class “LinkedListSample” is created with main() function.

Creation of Linked list :

LinkedList is created as String with an object linkList.

Inserting the data:

Using add() function,data is added to linkList.

Display the data:

 It uses get() function to get the data and display using print statement.

Remove a data:

 It uses the remove() function.

Iteration:

              Using iterator, it creates an object. A function hasNext() helps for iteration.

Program:

import java.util.LinkedList;

import java.util.Iterator;

public class LinkedListSample {

    public static void main(String[] args) {

        LinkedList<String> linkList = new LinkedList<>();

        // insert the data to node

        linkList.add("alpha");

        linkList.add("beta");

        linkList.add("Gamma");

        linkList.addFirst("Head Node");

        linkList.addLast("Last Node");

        // LinkedList printing statement

        System.out.println("The LinkedList is displayed: " + linkList);

        // get the elements andd display it

        String Element1 = linkList.getFirst();

        String Elementn = linkList.getLast();

        String Element2 = linkList.get(1);

        System.out.println("First Element is: " + Element1);

        System.out.println("Last Elements is: " + Elementn);

        System.out.println("Second Element is: " +Element2);

        // delete the elements

        linkList.removeFirst();

        linkList.removeLast();

        linkList.remove(1);

        // tranverse in LinkedList

        System.out.println("The iterated list after the removal of data");

        Iterator<String> iterator1 = linkList.iterator();

        while (iterator1.hasNext()) {

            System.out.println(iterator1.next());

        }

    }

}

Output:

C:\raji\blog>javac LinkedListSample.java

C:\raji\blog>java LinkedListSample

The LinkedList is displayed: [Head Node, alpha, beta, Gamma, Last Node]

First Element is: Head Node

Last Elements is: Last Node

Second Element is: alpha

The iterated list after the removal of data

alpha

Gamma

This is the way of implementing Linked list in java. Enjoy Coding!!!

List interface in java

              It is the fundamental concept of java collections framework. Main purpose of this concept is to traverse the list and its objects.

‘List interface’ – it deals with ordered sequence of elements. If you want to extend this interface for additional methods, just use the ‘Collection’ interface.

Collection interface has many methods for searching, traversing, viewing and particular position access.

Features:

  • ·       It supports null elements.
  • ·       It deals with ordered collection.
  • ·       Duplicates can be included.
  • ·       Mainly, a particular position is easily accessed.

How to implement the “List Interface”?

 To implement the list interface, you can use any of the data structure given below.

  • ·       Stack
  • ·       Vector
  • ·       Linked list
  • ·       ArrayList

A simple implementation of list interface using Array List and linked list is given below.

Steps to follow:

  • First create a class with main() function.
  • It has two parts. One is using an arrayList and another one is using linkedlist.

arrayList:

  • ·       An arraylist object is created. 3 data elements are added to arrayList.
  • ·       The array list is printed using the object.

Linkedlist:

  • ·       A new object is created and three elements are added. Finally,it was displayed using a linked list.

Program:

import java.util.*;

public class ListSample {

    public static void main(String[] args) {

        List<String> arrayList1 = new ArrayList<>();

        arrayList1.add("Cow");

        arrayList1.add("Goat");

        arrayList1.add("Sheep");

        System.out.println("The form animal ArrayList is: " + arrayList1);

        List<String> linkedList1 = new LinkedList<>();

        linkedList1.add("Lion");

        linkedList1.add("Tiger");

        linkedList1.add("Fox");

        System.out.println("The wild animal LinkedList is: " + linkedList1);

    }

}

The output is given below.

C:\raji\blog>javac ListSample.java

C:\raji\blog>java ListSample

The form animal ArrayList is: [Cow, Goat, Sheep]

The wild animal LinkedList is: [Lion, Tiger, Fox]

This is the basic implementation of list interface. Next, the way of doing the iteration is given below.

The iteraton:

              It includes the traversal on list interface. It has many methods listed below.

  • ·       next() – it gives you the next element.
  • ·       hasNext() – it gives you whether next element is available or not.
  • ·       remove() -it deletes an data.

Program uses these three methods:

import java.util.*;

public class IteratorEg {

    public static void main(String[] args) {

        List<String> list2 = new ArrayList<>();

        list2.add("alpha");

        list2.add("beta");

        list2.add("gamma");

        Iterator<String> iterator1 = list2.iterator();

        while (iterator1.hasNext()) {

            String data = iterator1.next();

            System.out.println(data);

             // Delete a data at iteration

            if (data.equals("beta")) {

                iterator1.remove();

            }

        }

        System.out.println("Here is the list after iteration: " + list2);

    }

}

Output:

C:\raji\blog>javac IteratorEg.java

C:\raji\blog>java IteratorEg

alpha

beta

gamma

Here is the list after iteration: [alpha, gamma]

These are the ways to use the iterators in list interface.Happy coding!!!!

File handling in java

             Files are essentials in software implementation. File handling deals with creation of a file, reading the contents of a file, writing the contents to a file and deleting a file.

Built in package in java which supports the file operations is “java.io”.

How to implement the file operations in java?

There are four operations in file handling listed as follows.

 1.    Creating a file

 2.    Reading the contents in a file

 3.   Writing the contents to a file

 4.    Deleting a file

1.Creating a file in java:

              It includes the below steps.

Steps:

  • Include the builtin packages.
  • Create a  class with main() function. from the File, create a object myFile1.
  • Using the object, call the createNewFile() function.

import java.io.File;

import java.io.IOException;

public class NewFileCreation {

    public static void main(String[] args) {

        try {

            File myFile1 = new File("newfile.txt");

            if (myFile1.createNewFile()) {

                System.out.println("File created: " + myFile1.getName());

            } else {

                System.out.println("File already exists.");

            }

        } catch (IOException e) {

            System.out.println("An error occurred.");

            e.printStackTrace();

        }

    }

}

Output:

C:\raji\blog>javac NewFileCreation.java

C:\raji\blog>java NewFileCreation

File created: abc.txt

2. Reading the contents in a file:

  •  First create contents to the file “abc.txt”. For example,"This file is created by NewFileCreation.java".
  • This program has two reader. One is for FileReader and another one is BufferedReader.
  • FileReader object reads  the file “abc.txt” and store it to bufferedReader object.
  • Using a while loop, the data is read from file and displayed in the output screen.

Program:

import java.io.FileReader;

import java.io.BufferedReader;

import java.io.IOException;

public class ReadIt {

    public static void main(String[] args) {

        try {

            FileReader myReader1 = new FileReader("abc.txt");

            BufferedReader bufferedReader1 = new BufferedReader(myReader1);

            String data;

            while ((data = bufferedReader1.readLine()) != null) {

                System.out.println(data);

            }

            bufferedReader1.close();

        } catch (IOException e) {

            System.out.println("An error occurred.");

            e.printStackTrace();

        }

    }

}

Here is the output.

C:\raji\blog>javac ReadIt.java

C:\raji\blog>java ReadIt

"This file is created by NewFileCreation.java"

These are the creation and reading the contents from file using java. Keep Coding!!!