Friday, 1 August 2014

Convert List to Set

Simplest way to convert List to set is pass the List instance to the Set Constructor.

Ex:
Set mySet = new HashSet<> (myList)

But one thing to remember is, Set won't allow duplicates. Duplication is identified by using in combination with equals and hashCode method. If you don't override both the methods then duplicates store into the set.

Ex: Without overriding equals and hashCode
public class Employee{
    String name;
    Integer id;
    
    Employee(int id, String name){
        this.name = name;
        this.id = id;
    }
    
    @Override
    public String toString(){
        return id +" " + name;
    }
}

import java.util.*;

public class ListToSet {
    public static void main(String args[]){
        List<Employee> myList = new ArrayList<> ();
        Set<Employee> mySet;
        
        Employee e1 = new Employee(1, "Krishna");
        Employee e2 = new Employee(2, "Arjun");
        Employee e3 = new Employee(1, "Krishna");
        
        myList.add(e1);
        myList.add(e2);
        myList.add(e3);
        
        mySet = new HashSet<> (myList);
        
        Iterator<Employee> iter = mySet.iterator();
        
        while(iter.hasNext()){
            System.out.println(iter.next());
        }
        
    }
}

Output
1 Krishna
1 Krishna
2 Arjun

As you observe the output, Employee with id '1' and name 'Krishna' stored twice in the set. To resolve the issue Employee class must override hashCode and equals methods.

Ex: Overriding equals and hashCode
import java.util.Objects;

public class Employee{
    String name;
    Integer id;
    
    Employee(int id, String name){
        this.name = name;
        this.id = id;
    }
    
    @Override
    public String toString(){
        return id +" " + name;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 29 * hash + Objects.hashCode(this.name);
        hash = 29 * hash + Objects.hashCode(this.id);
        return hash;
    }
    
    @Override
    public boolean equals(Object obj){
        if(obj!=null)
            if(obj instanceof Employee){
                Employee emp = (Employee) obj;
                boolean a = Objects.equals(id, emp.id);
                boolean b = (name == null ? emp.name == null : name.equals(emp.name));
                return ( a && b);
            }
        return false;                
    }
}

Run ListToSet again, then no duplicates are stored to the Set.

Related Links




                                                             Home

Cloning Vs Creating new Object

  1. Using clone, we can initialize the fields of an instance to be identical to the original instance.
  2. In case of creating identical objects cloning is always faster. Instead of reading identical object from database or file, it is always better to create an identical object from existing one.
import java.io.FileNotFoundException;
import java.math.BigInteger;
import java.util.*;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class BigObject implements Serializable, Cloneable{
    BigInteger id;
    Random rand;
    
    BigObject(){
        rand = new Random();
        id = new BigInteger(100000000, rand);
    }
    
    public static BigObject createObject() throws FileNotFoundException, IOException{
        FileOutputStream fileOut = new FileOutputStream("obj.ser");
        BigObject obj = new BigObject();
        try (ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
             out.writeObject(obj);
        }
        fileOut = null;
        return obj;
    }
    
    @Override
    public BigObject clone() throws CloneNotSupportedException{
        return (BigObject)super.clone();
    }
}

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class CloningVsCreating {
    public static void main(String args[]) throws Exception{
        BigObject obj1 = BigObject.createObject();
        
        long time1 = System.currentTimeMillis();
        FileInputStream fileIn = new FileInputStream("obj.ser");
        ObjectInputStream in = new ObjectInputStream(fileIn);
        BigObject obj2 = (BigObject)in.readObject();
        long time2 = System.currentTimeMillis();
        
        BigObject obj3 = obj1.clone();
        long time3 = System.currentTimeMillis();
        
        System.out.println("Time taken to create new object " + (time2-time1));
        System.out.println("Time to create object using cloning " + (time3-time2));
        
        System.out.println(obj1.id.equals(obj2.id));
        System.out.println(obj1.id.equals(obj3.id));
    }
}

Output
Time taken to create new object 128
Time to create object using cloning 0
true
true




                                                             Home

getRealPath (String path)

public String getRealPath(String path)
getRealPath method declared in ServletContext interface. The getRealPath method takes a String argument and returns a String representation of a file on the local file system to which a path corresponds.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form method="get" action="/servlet/GetRealPath">
            <input type="submit">
        </form>
    </body>
</html>

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>GetRealPath</servlet-name>
        <servlet-class>GetRealPath</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>GetRealPath</servlet-name>
        <url-pattern>/GetRealPath</url-pattern>
    </servlet-mapping>
</web-app>

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;

public class GetRealPath extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
       try(PrintWriter out = res.getWriter()) {
            res.setContentType("text/html");
            ServletContext context = req.getServletContext();
            String realPath = context.getRealPath("main.jsp");
            
            String str = "<html>" +
                         "<head>" +
                         "<title> Hello World </title>" +
                         "</head>" +
                         "<body>" +
                         "<h1>  <br />" + realPath +
                         "</h1> </body>" +
                         "</html>";
            out.println(str);
       }
   } 
}



Prevoius                                                 Next                                                 Home

Path Translation Methods

There are two convenience methods in the API which allow the Developer to obtain the file system path equivalent to a particular path. 

    ServletContext.getRealPath
    HttpServletRequest.getPathTranslated

In situations where the servlet container cannot determine a valid file path for these methods, such as when the Web application is executed from an archive, on a remote file system not accessible locally, or in a database, these methods return null.


Prevoius                                                 Next                                                 Home

getPathInfo()

public String getPathInfo()
Returns any extra path information associated with the URL the client sent when it made this request. The extra path information follows the servlet path but precedes the query string and will start with a "/" character. This method returns null if there was no extra path information.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Get Books</title>
    </head>
    <body>
        <form method="get" action="/servlet/GetBooks/GetMyBook">
           <select name="author">
                <option>Yashavant Kanetkar</option>
                <option>Deitel</option>
                <option>Herbert Schildt</option>
                <option>Bruce Eckel</option>
          </select> 
            <input type="submit" value="submit" />
        </form>
    </body>
</html>


web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>GetBooks</servlet-name>
        <servlet-class>GetBooks</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>GetBooks</servlet-name>
        <url-pattern>/GetBooks/GetMyBook</url-pattern>
    </servlet-mapping>
</web-app>

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

public class GetBooks extends HttpServlet {
    
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
       PrintWriter out = res.getWriter();
       String author;
       List<String> books;
       Iterator<String> iter;
       StringBuilder body = new StringBuilder();
       res.setContentType("text/html");
      
       String header = "<html>" +
                    "<head>" +
                    "<title> Hello World </title>" +
                    "</head>" +
                    "<body>" +
                    "<h1> <br />";                     
       String footer = "</h1> </body>" +
                    "</html>";
       
       String contextPath = req.getContextPath();
       String servletPath = req.getServletPath();
       String pathInfo = req.getPathInfo();
       
       body.append("ContextPath ").append(contextPath).append("<br />");
       body.append("Servlet Path ").append(servletPath).append("<br />");
       body.append("Path Info ").append(pathInfo).append("<br />");
       out.println(header + "" + body + footer);
    }
}

Output





Prevoius                                                 Next                                                 Home

getServletPath()

public String getServletPath()
Returns the part of this request's URL that calls the servlet. This method will return an empty string ("") if the servlet used to process this request was matched using the "/*" pattern.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Get Books</title>
    </head>
    <body>
        <form method="get" action="/servlet/GetBooks/GetMyBook">
           <select name="author">
                <option>Yashavant Kanetkar</option>
                <option>Deitel</option>
                <option>Herbert Schildt</option>
                <option>Bruce Eckel</option>
          </select> 
            <input type="submit" value="submit" />
        </form>
    </body>
</html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>GetBooks</servlet-name>
        <servlet-class>GetBooks</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>GetBooks</servlet-name>
        <url-pattern>/GetBooks/GetMyBook</url-pattern>
    </servlet-mapping>
</web-app>

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

public class GetBooks extends HttpServlet {
    
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
       PrintWriter out = res.getWriter();
       String author;
       List<String> books;
       Iterator<String> iter;
       StringBuilder body = new StringBuilder();
       res.setContentType("text/html");
      
       String header = "<html>" +
                    "<head>" +
                    "<title> Hello World </title>" +
                    "</head>" +
                    "<body>" +
                    "<h1> <br />";                     
       String footer = "</h1> </body>" +
                    "</html>";
       
       String contextPath = req.getContextPath();
       String servletPath = req.getServletPath();
       String pathInfo = req.getPathInfo();
       
       body.append("ContextPath ").append(contextPath).append("<br />");
       body.append("Servlet Path ").append(servletPath).append("<br />");
       body.append("Path Info ").append(pathInfo).append("<br />");
       out.println(header + "" + body + footer);
    }
}

Output






Prevoius                                                 Next                                                 Home

getContextPath()

public String getContextPath()
Returns the portion of the request URI that indicates the context of the request. For servlets in the default (root) context, this method returns "".

Note:
It is possible that a servlet container may match a context by more than one context path. In such cases this method will return the actual context path used by the request and it may differ from the path returned by the ServletContext.getContextPath() method. The context path returned by ServletContext.getContextPath() should be considered as the prime or preferred context path of the application.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Get Books</title>
    </head>
    <body>
        <form method="get" action="/servlet/GetBooks/GetMyBook">
           <select name="author">
                <option>Yashavant Kanetkar</option>
                <option>Deitel</option>
                <option>Herbert Schildt</option>
                <option>Bruce Eckel</option>
          </select> 
            <input type="submit" value="submit" />
        </form>
    </body>
</html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>GetBooks</servlet-name>
        <servlet-class>GetBooks</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>GetBooks</servlet-name>
        <url-pattern>/GetBooks/GetMyBook</url-pattern>
    </servlet-mapping>
</web-app>

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

public class GetBooks extends HttpServlet {
    
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
       PrintWriter out = res.getWriter();
       String author;
       List<String> books;
       Iterator<String> iter;
       StringBuilder body = new StringBuilder();
       res.setContentType("text/html");
      
       String header = "<html>" +
                    "<head>" +
                    "<title> Hello World </title>" +
                    "</head>" +
                    "<body>" +
                    "<h1> <br />";                     
       String footer = "</h1> </body>" +
                    "</html>";
       
       String contextPath = req.getContextPath();
       String servletPath = req.getServletPath();
       String pathInfo = req.getPathInfo();
       
       body.append("ContextPath ").append(contextPath).append("<br />");
       body.append("Servlet Path ").append(servletPath).append("<br />");
       body.append("Path Info ").append(pathInfo).append("<br />");
       out.println(header + "" + body + footer);
    }
}

Output





Prevoius                                                 Next                                                 Home