Friday, 29 July 2016

Implement custom iterator in Java

In this post, I am going to explain how to implement custom iterator and solve one interview question using iterator.

What is iterator?
Iterator is used to traverse the collection of elements. There is also a legacy class called Enumeration, it is also used to traverse collection of elements. Only difference is by using iterator you can remove an element while traversing, by using enumerator you can’t.

Let me brief the methods in iterator interface.
Method
Description
boolean hasNext()
Returns true if the iteration has more elements.
E next()
Returns the next element in the iteration.
default void remove()
Removes from the underlying collection the last element returned by this iterator. Java provides default implementation for this method. The default implementation throws an instance of UnsupportedOperationException and performs no other action.

Iterable interface
All the Java collections implementing Iterable interface, to return an iterator. Implementing this interface allows an object to be the target of the "foreach" statement. Following table summarizes the methods in Iterable interface.

Method
Description
Iterator<T> iterator()
Returns an iterator over a set of elements of type T.

Now lets come to the problem, I want to implement my own iterator. Suppose my collection has elements like 1, 2, 3, 4, 5, 6, 7, 8, 9. My iterator should traverse the elements at even positions like 1(is at 0th position), 3(is at 2nd position), 5, 7, 9.


I defined EvenList class like below.
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

public class EvenList<T> implements Iterable<T> {
 private List<T> list;

 EvenList(List<T> list) {
  this.list = list;
 }

 public Iterator<T> iterator() {
  return new EvenIterator<T>();
 }

 @SuppressWarnings("hiding")
 private class EvenIterator<T> implements Iterator<T> {
  int size = list.size();
  int currentPointer = 0;

  public boolean hasNext() {
   return (currentPointer < size);
  }

  public T next() {
   if (!hasNext()) {
    throw new NoSuchElementException();
   }

   @SuppressWarnings("unchecked")
   T val = (T) list.get(currentPointer);
   currentPointer += 2;

   return val;
  }

 }

}

Total logic is in the next() method, here I am checking for an element in the collection using hasNext() method, it it returns false, I am throwing NoSuchElementException(). If element exists, then I am saving current element to a temporary variable and incrementing the currentPointer to 2.

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class TestEvenList {
 public static void main(String args[]) {
  List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

  EvenList<Integer> myList = new EvenList(list);

  Iterator<Integer> iter = myList.iterator();
  while (iter.hasNext()) {
   System.out.println(iter.next());
  }
 }
}


Run above program, you will get following output.

Wednesday, 27 July 2016

ABS() function



ABS() function returns the absolute value of a number.

mysql> SELECT ABS(0);
+--------+
| ABS(0) |
+--------+
|      0 |
+--------+
1 row in set (0.00 sec)

mysql> SELECT ABS(-199);
+-----------+
| ABS(-199) |
+-----------+
|       199 |
+-----------+
1 row in set (0.01 sec)

mysql> SELECT ABS(199);
+----------+
| ABS(199) |
+----------+
|      199 |
+----------+
1 row in set (0.00 sec)


Let me give an example. I am going to use following sample data.
CREATE TABLE blog(
  postId int PRIMARY KEY,
  postTitle VARCHAR(25),
  duration DECIMAL(6, 2)
);

CREATE TABLE post_info(
        postId int PRIMARY KEY,
        likes int,
        doslikes int,
        shares int
);

INSERT INTO blog VALUES(1, "Introduction To Java", 23.56);
INSERT INTO blog VALUES(2, "Hello World to Haskell", 8.54);
INSERT INTO blog VALUES(3, "SQL Queries", 104.43);
INSERT INTO blog VALUES(4, "Static Vs Dynamic", 65.43);
INSERT INTO blog VALUES(5, "IJSON", 65.09);

INSERT INTO post_info VALUES(1, 123, 32, 10);
INSERT INTO post_info VALUES(2, 654, 59, 8);
INSERT INTO post_info VALUES(3, 76, 132, 80);
INSERT INTO post_info VALUES(4, 987, 9, 100);
INSERT INTO post_info VALUES(5, 87, 65, 5);

mysql> SELECT * FROM blog;
+--------+------------------------+----------+
| postId | postTitle              | duration |
+--------+------------------------+----------+
|      1 | Introduction To Java   |    23.56 |
|      2 | Hello World to Haskell |     8.54 |
|      3 | SQL Queries            |   104.43 |
|      4 | Static Vs Dynamic      |    65.43 |
|      5 | IJSON                  |    65.09 |
+--------+------------------------+----------+
5 rows in set (0.00 sec)

mysql>
mysql> SELECT * FROM post_info;
+--------+-------+----------+--------+
| postId | likes | doslikes | shares |
+--------+-------+----------+--------+
|      1 |   123 |       32 |     10 |
|      2 |   654 |       59 |      8 |
|      3 |    76 |      132 |     80 |
|      4 |   987 |        9 |    100 |
|      5 |    87 |       65 |      5 |
+--------+-------+----------+--------+
5 rows in set (0.00 sec)


Get absolute difference between every post, which exist in table blog.



SELECT blg.postTitle, ABS(post.likes-post.doslikes) AS "Difference between likes and dislikes"
FROM blog AS blg
JOIN post_info AS post
ON blg.postId = post.postId;






Previous                                                 Next                                                 Home