Similarities between TreeMap and TreeSet in Java

  1. Both TreeMap and TreeSet are sorted data structure, which means they keep there element in predefined Sorted order. Sorting order can be natural sorting order defined by Comparable interface or custom sorting Order defined by Comparator interface. Both TreeMap and TreeSet has overloaded constructor which accept a Comparator, if provided all elements inside TreeSet or TreeMap will be compared and Sorted using this Comparator.
  2. Both TreeSet and TreeMap implements base interfaces e.g. TreeSet implements Collection and Set interface so that they can be passed to method where a Collection is expected and TreeMap implements java.util.Map interface, which means you can pass it when a Map is expected
  3. TreeSet is practically implemented using TreeMap instance, similar to HashSet which is internally backed by HashMap instance.
  4. Both TreeMap and TreeSet are non synchronized Collection, hence can not be shared between multiple threads. You can make both TreeSet and TreeMap synchronized by wrapping them into Synchronized collection by calling Collections.synchroinzedMap() method.
  5. Iterator returned by TreeMap and TreeSet are fail-fast, means they will throw ConcurrentModificationException when TreeMap or TreeSet is modified structurally once Iterator is created.
  6. Both TreeMap and TreeSet are slower than there Hash counter part like HashSet and HashMap and instead of providing constant time performance for add, remove and get operation they provide performance in O(log(n)) order.

TreeSet vs TreeMap

  1. Major difference between TreeSet and TreeMap is that TreeSet implements Set interface while TreeMap implements Map interface in Java.
  2. TreeMap and TreeSet is the way they store objects. TreeSet stores only one object while TreeMap uses two objects called key and Value. Objects in TreeSet are sorted while keys in TreeMap remain in sorted Order.
  3. former implements NavigableSet while later implements NavigableMap in Java.
  4. duplicate objects are not allowed in TreeSet but duplicates values are allowed in TreeMap.

1.How to get elements from HashMap

public static void printMap(Map mp) 
{
    Iterator it = mp.entrySet().iterator();

    while (it.hasNext()) 
    {
        Map.Entry pairs = (Map.Entry)it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());

        //Avoids a ConcurrentModificationException
        it.remove(); 
    }
}

2.Adding keys to HashMap Finding Next Key
To find the next key while using HashMap with Integer as Key the following function can be used.

  1. Iterate through List of Keys
  2. Sort the Keys
  3. Find the Highest value by looking into Key at size-1
  4. The next key to be used is received by adding 1 to Key(lastMaxElem) at size-1
private Integer getNextKey()
{
    List<Integer> keyList = new ArrayList<Integer>();
    int lastMaxElem = 0;
		
    HashMap WaterfallHM = (HashMap) getFromWorkFlowScope("WaterfallHM");		
    Set<Integer> keys = WaterfallHM.keySet();
        
    for ( Integer key : keys) {
	keyList.add(key);
    }
		
    Collections.sort(keyList); // Sort the arraylist
    lastMaxElem = keyList.get(keyList.size() - 1);
    lastMaxElem++; 
		
    return new Integer(lastMaxElem);
}

3.How to Initialize a Constants in HashMap

public class Test 
{
    private static final Map<Integer, String> MY_MAP = createMap();

    private static Map<Integer, String> createMap() {
        Map<Integer, String> result = new HashMap<Integer, String>();
        result.put(1, "one");
        result.put(2, "two");
        return Collections.unmodifiableMap(result);
    }
}

4.Why Map Interface doesnot extend Collections Framework
Collection assume elements of one value. Map assumes entries of key/value pairs. They could have been engineered to re-use the same common interface however some methods they implement are incompatible e.g.

Collection.remove(Object) - removes an element.
Map.remove(Object) - removes by key, not by entry.

There are some methods in common; size(), isEmpty(), clear(), putAll/addAll()

Collection interface is largely incompatible with the Map interface. If Map extended Collection, what would the add(Object) method do

5.Why need ConcurrentHashMap and CopyOnWriteArrayList
he synchronized collections classes, Hashtable, and Vector, and the synchronized wrapper classes, Collections.synchronizedMap() and Collections.synchronizedList(), provide a basic conditionally thread-safe implementation of Map and List. However, several factors make them unsuitable for use in highly concurrent applications, for example, their single collection-wide lock is an impediment to scalability and it often becomes necessary to lock a collection for a considerable time during iteration to prevent ConcurrentModificationException.ConcurrentHashMap(uses Segments) and CopyOnWriteArrayList implementations provide much higher concurrency while preserving thread safety, with some minor compromises in their promises to callers.

Problems
Q1.Calculate total distance traveled by beeTwo trains are on the same track and they are coming toward each other. The speed of the first train is 50 KMs/h and the speed of second train is 70 KMs/h. A bee starts flying between the trains when the distance between two trains is 100 KMs. The bee first flies from the first train to the second train. Once it reaches the second train, it immediately flies back to the second train … and so on until trains collide. Calculate the total distance traveled by the bee. Speed of bee is 80 KMs/h.

Solutions
Calculate total distance traveled by bee

                                        80km/h
                        50km/h       <---------->        70km/h 
------------------------Train1->         bee             <-Train2-------------------------
                                <----------------------->  
                                        100km/h

Time left for the train to meet each other = 100/(50+70) = 100/120=0.83 = 49.8 Minutes
The Fly will zigzag between train till that time at speed of 80km/h = (80/60)*49.8 = 1.33*49.8 = 66.4KM

Lets solve the same problem with some easy values as below

                                        40km/h
                        20km/h       <---------->        20km/h 
------------------------Train1->         bee             <-Train2-------------------------
                                <----------------------->  
                                        100km/h

Time left for the train to meet each other = 100/(20+20) = 100/40=2.5(2Hrs30 Minutes)
The Fly will zigzag between train till that time at speed of 40km/h = (40/60)*150 = 0.66*150 = 100KM

In Spring MVC Exceptions can be handled at three levels.

1.Controller Based
We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation. This annotation takes the Exception class as an argument. So if we have defined one of these for Exception class, then all the exceptions thrown by our request handler method will have handled.
These exception handler methods are just like other request handler methods and we can build error response and respond with a different error page. We can also send a JSON error response, that we will look later on in our example.

@ExceptionHandler({SpringException.class})
.
.
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
@ExceptionHandler({SpringException.class})
public String addStudent(@ModelAttribute("HelloWeb") Student student, ModelMap model) 
{
 if (student.getName().length() < 5)  
  throw new SpringException("Given name is too short");
 else
  model.addAttribute("name", student.getName());
 
 if (student.getAge() < 10)
  throw new SpringException("Given age is too low");
 else
  model.addAttribute("age", student.getAge());

  model.addAttribute("id", student.getId());
  return "result";
}
.
.
.

If there are multiple exception handler methods defined, then handler method that is closest to the Exception class is used. For example, if we have two handler methods defined for IOException and Exception and our request handler method throws IOException, then the handler method for IOException will get executed.

2.Global Exception Handler-The handler methods in Global Controller Advice is same as Controller based exception handler methods and used when controller class is not able to handle the exception.@ControllerAdvice is a annotation provided by Spring allowing you to write global code that can be applied to a wide range of controllers, varying from all controllers to a chosen package or even a specific annotation. The annotation could be applied at Package Level, Class Level and at Annotation Level.

Package Level Application

@ControllerAdvice("my.chosen.package")
@ControllerAdvice(value = "my.chosen.package")
@ControllerAdvice(basePackages = "my.chosen.package")

Package Level Application – This will apply across all the classes inside the package where MyClass.class is placed.

@ControllerAdvice(basePackageClasses = MyClass.class)

Controller Level
Controller advice can be limited to certain controllers (not methods) by using one of the values of the @ControllerAdvice annotation, e.g.

@ControllerAdvice(assignableTypes = {MyController1.class, MyController2.class})

Controller identified by Annotation
If you want to apply it to controllers with certain annotations. The below snippet would only assist controllers annotated with @RestController (which it covers by default) but will not include @Controller annotated classes.

@ControllerAdvice(annotations = RestController.class)

3.HandlerExceptionResolver – can be implemented by the application to resolve exceptions thrown during processing an HTTP request. The exception can be thrown by one of the application’s handler methods or outside of it but during processing a request. The method, HandlerExceptionResolver#resolveException(), returns an instance of ModelAndView specifying an error page. The Implementations are typically registered as beans in the application context. The application registered HandlerExceptionResolvers will only be invoked if the exception is not already handled by the default HandlerExceptionResolvers. We can, however, change the order of the resolvers so that a given resolver can be invoked first.

@ExceptionHandler vs HandlerExceptionResolver vs @ControllerAdvice
@ExceptionHandler works at the Controller level and it is only active for that particular Controller, not globally for the entire application.

@ControllerAdvice used for global error handling in the Spring MVC application.It also has full control over the body of the response and the status code.

HandlerExceptionResolver-This will resolve any exception thrown by the application. It is used to resolve standard Spring exceptions to their corresponding HTTP Status Codes. It does not have control over the body of the response, means it does not set anything to the body of the Response.It does map the status code on the response but the body is null.

Posted in MVC.

Questions

  1. Three ants are sitting at the three corners of an equilateral triangle. Each ant starts randomly picks a direction and starts to move along the edge of the triangle. What is the probability that none of the ants collide?

Solutions
The ants can only avoid a collision if they all decide to move in the same direction (either clockwise or anti-clockwise). So what is the probability of taking Clockwise direction? 1/2 (0.5).What is the probability of all ants taking the same direction?

Probability of taking the Clockwise direction      = 0.5x0.5x0.5
Probability of taking the Anti-Clockwise direction = 0.5x0.5x0.5
Probability of taking the Same Direction = 0.5x0.5x0.5+0.5x0.5x0.5=0.125+0.125=0.25

Problems

  1. Find the Diagonal difference in the Matrix? Add the Diagonal values and subtract them from right to left and left to right? Print the absolute difference as output

Solutions

Input

 11  2   4 
 4   5   6
 10  8  -12 

Solution

(11+5+-12)-(4+5+10) 
(4)-(19)
(-15)

Output

15

DiagonalDiff.java

class DiagonalDiff
{
 public static int difference(int arr[][], int n) 
 {
  int d1 = 0, d2 = 0;

  for (int i = 0; i < n; i++) 
  {
   d1 += arr[i][i];
   d2 += arr[i][n - i - 1];
  }
  return Math.abs(d1 - d2);
 }
 
 public static void main(String[] args) 
 {
  int n = 3;

  int arr[][] = 
  {
   {11, 2, 4}, 
   {4 , 5, 6}, 
   {10, 8, -12} 
  };

  System.out.print(difference(arr, n));
 }
}

How to Search for Product with least cost from List? I have a List of Speakers in List. I want to get the speaker with the least cost.

Speakers.java

package com.mugil.bean;

public class Speakers {
 private Integer speakerID;
 private String companyName;
 private Integer price;
 private String sellerName;

 public Speakers(Integer pSpeakerId, String pcompanyName, Integer pPrice, String psellerName) {
  this.speakerID = pSpeakerId;
  this.companyName = pcompanyName;
  this.price = pPrice;
  this.sellerName = psellerName;
 }

 public int getSpeakerID() {
  return speakerID;
 }
 public void setSpeakerID(int speakerID) {
  this.speakerID = speakerID;
 }
 public String getCompanyName() {
  return companyName;
 }
 public void setCompanyName(String companyName) {
  this.companyName = companyName;
 }
 public int getPrice() {
  return price;
 }
 public void setPrice(int price) {
  this.price = price;
 }

 public String getSellerName() {
  return sellerName;
 }

 public void setSellerName(String sellerName) {
  this.sellerName = sellerName;
 }

 @Override
 public String toString() {
  return "Speakers [speakerID=" + speakerID + ", companyName=" + companyName + ", price=" + price +
   ", sellerName=" + sellerName + "]";
 }
}

SearchSpeakers.java

package com.mugil.test;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import com.mugil.bean.Speakers;

public class SearchSpeakers {

 public static void main(String[] args) {
  Speakers objSpeaker1 = new Speakers(101, "JBL Go", 120, "Amazon");
  Speakers objSpeaker2 = new Speakers(102, "Panasonic", 420, "Amazon");
  Speakers objSpeaker3 = new Speakers(103, "JBL Go", 900, "Flipkart");
  Speakers objSpeaker4 = new Speakers(104, "JBL Go", 120, "Amazon");
  Speakers objSpeaker5 = new Speakers(105, "JBL Go", 350, "Amazon");
  Speakers objSpeaker6 = new Speakers(101, "Philips", 120, "EBay");
  Speakers objSpeaker7 = new Speakers(102, "JBL Go", 125, "Ebay");
  Speakers objSpeaker8 = new Speakers(103, "JBL Go", 35, "Smart Shoppe");
  Speakers objSpeaker9 = new Speakers(104, "Panasonic", 80, "Amazon");
  Speakers objSpeaker10 = new Speakers(105, "Philips", 180, "Amazon");

  List < Speakers > arrSpeakers = new ArrayList < Speakers > ();

  arrSpeakers.add(objSpeaker1);
  arrSpeakers.add(objSpeaker2);
  arrSpeakers.add(objSpeaker3);
  arrSpeakers.add(objSpeaker4);
  arrSpeakers.add(objSpeaker5);
  arrSpeakers.add(objSpeaker6);
  arrSpeakers.add(objSpeaker7);
  arrSpeakers.add(objSpeaker8);
  arrSpeakers.add(objSpeaker9);
  arrSpeakers.add(objSpeaker10);

  Comparator < Speakers > spkComparator = (Speakers objSpeaker1a, Speakers objSpeaker2a) -> objSpeaker1a.getPrice() - objSpeaker2a.getPrice();

  arrSpeakers.stream().sorted(spkComparator).collect(Collectors.groupingBy(Speakers::getCompanyName)).values()
   .stream().forEach(searchedModel -> System.out
    .println("Speaker with Lowest Cost" + searchedModel.stream().findFirst()));
 }
}
arrSpeakers.stream().sorted(spkComparator).collect(Collectors.groupingBy(Speakers::getCompanyName)).values()
   .stream().forEach(searchedModel -> System.out
    .println("Speaker with Lowest Cost" + searchedModel.stream().findFirst()));

arrSpeakers.stream() – Convert to Stream
arrSpeakers.stream().sorted(spkComparator) – Sorts the list by price
arrSpeakers.stream().sorted(spkComparator).collect(Collectors.groupingBy(Speakers::getCompanyName)) – Groups the Sorted List by Company Name
arrSpeakers.stream().sorted(spkComparator).collect(Collectors.groupingBy(Speakers::getCompanyName)).values()
.stream()
– Convert the Sorted List into Stream

The above code could be rewritten as follows

//Sort by Price and group by company name
Stream objStream = arrSpeakers.stream()
                              .sorted(spkComparator)
                              .collect(Collectors.groupingBy(Speakers::getCompanyName)).values();

//Loop through Stream of List and print the first one
objStream.forEach(listOfStudent -> System.out.println((ArrayList)listOfStudent.stream().findFirst()));

Output

Speaker with Lowest CostOptional[Speakers [speakerID=101, companyName=Philips, price=120, sellerName=EBay]]
Speaker with Lowest CostOptional[Speakers [speakerID=104, companyName=Panasonic, price=80, sellerName=Amazon]]
Speaker with Lowest CostOptional[Speakers [speakerID=103, companyName=JBL Go, price=35, sellerName=Smart Shoppe]]

Basics of Minimalism

  1. Retain the essential, let go of other things
  2. Put it in Cardboard box, 90/90 day rule, If you dont use it more than 90 days let it go
  3. Cut on Social media, Check once in morning and once in evening
  4. Cut back bad habits. Develope good habits in Health, Money
  5. Remove mental clutter and get rid of things which never useful
  6. Make Priorities before starting to work

The heart of any Hibernate application is in its configuration. There are two pieces of configuration required in any Hibernate application: one creates the database connections, and the other creates the object-to-table mapping

null

To create a connection to the database, Hibernate must know the details of our database, tables, classes, and other mechanics. This information is ideally provided as an XML file (usually named hibernate.cfg.xml) or as a simple text file with name/value pairs (usually named hibernate.properties).
In XML style. We name this file hibernate.cfg.xml so the framework can load this file automatically.

hibernate.cfg.xml

<hibernate-configuration>  
    <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">pass</property>
         
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
 
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 
        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
 
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
 
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>
         
        <!-- Name of the Annotated Entity class -->
        <mapping class="com.mugil.dto.UserDetails"/>
    </session-factory>
</hibernate-configuration>

hibernate.properties

hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate.connection.url = jdbc:mysql://localhost:3307/JH
hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

We must let Hibernate know our mapping definition files by including an element mapping property in the previous config file, as shown here:
hibernate.cfg.xml

<hibernate-configuration>
 <session-factory>
 ...
 <mapping resource="table1.hbm.xml" />
 <mapping resource="table2.hbm.xml" />
 <mapping resource="table3.hbm.xml" />
 </session-factory>
</hibernate-configuration>

Once we have the connection configuration ready, the next step is to prepare the table1.hbm.xml file consisting of object-table mapping definitions
XML Mapping

<hibernate-mapping>
 <class name="com.java.latte.table1" table="TABLE1">
 <id name="id" column="ID">
 <generator class="native"/>
 </id>
 <property name="title" column="TITLE"/>
 <property name="director" column="DIRECTOR"/>
 <property name="synopsis" column="SYNOPSIS"/>
 </class>
</hibernate-mapping>
  1. The Hibernate framework reads the hibernate.cfg.xml file to create a SessionFactory, which is thread-safe global factory class for creating Sessions. We should ideally create a single SessionFactory and share it across the application.SessionFactory is defined for one, and only one, database.
  2. SessionFactory is to create Session objects.It is the Session’s job to take care of all database operations such as saving, loading, and retrieving records from relevant tables.Session objects are not thread-safe and therefore should not be shared across different classes.
  3. The Session wraps the underlying JDBC connection or J2EE data source, and it serves as a first-level cache for persistent objects bound to it.
  4. Hibernate specifies how each object state is retrieved and stored in the database via an XML configuration file. Hibernate mappings are loaded at startup and are cached in the SessionFactory. Each mapping specifies a variety of parameters related to the persistence lifecycle of instances of the mapped class

null

More on hibernate Object States here
More on hibernate Object types here

Filters

  1. A filter as the name suggests is a Java class executed by the servlet container for each incoming http request and for each http response. This way, is possible to manage HTTP incoming requests before them reach the resource, such as a JSP page, a servlet or a simple static page; in the same way is possible to manage HTTP outbound response after resource execution.
  2. The filter runs in the web container so its definition will also be contained in the web.xml file
  3. filer include three main methods:
    • init: executed to initialize filter using init-param element in filter definition
    • doFilter: executed for all HTTP incoming request that satisfy “url-pattern”
    • release resources used by the filter

web.xml

<filter>
    <filter-name>CORSFilter</filter-name>
    <filter-class>com.listfeeds.components.CORSFilter</filter-class>
    <init-param>
        <param-name>fake-param</param-name>
        <param-value>fake-param-value</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

TestFilter.java

package com.listfeeds.filters;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

public class TestFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

Filters can perform many different types of functions.

  1. Authentication-Blocking requests based on user identity.
  2. Logging and auditing-Tracking users of a web application.
  3. Image conversion-Scaling maps
  4. Data compression-Making downloads smaller
  5. Localization-Targeting the request and response to a particular locale

Request Filters can:

  1. perform security checks
  2. reformat request headers or bodies
  3. audit or log requests

Response Filters can:

  1. Compress the response stream
  2. Append or alter the response stream
  3. Create a different response altogether

Interceptors

  1. Spring Interceptors are similar to Servlet Filters but they acts in Spring Context so are many powerful to manage HTTP Request and Response but they can implement more sophisticated behavior because can access to all Spring context.
  2. Developers can invoke interceptor methods in conjunction with method invocations or lifecycle events on an associated target class. Common uses of interceptors are logging, auditing, or profiling.
  3. Spring interceptor execute in Spring context so they have be defined in rest-servlet.xml file:
  4. The interceptor include three main methods:
    • preHandle: executed before the execution of the target resource
    • afterCompletion: executed after the execution of the target resource (after rendering the view)
    • posttHandle: Intercept the execution of a handler

rest-servlet.xml

<mvc:interceptors>
    <bean class="com.listfeeds.interceptors.LogContextInterceptor" />
    <bean class="com.listfeeds.interceptors.TimedInterceptor" />
</mvc:interceptors>

LogContextInterceptor.java

public class LogContextInterceptor extends HandlerInterceptorAdapter 
{
 private static final Logger log = LoggerFactory.getLogger(LogContextInterceptor.class);

 @Override
 public void afterCompletion(
  HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
 throws Exception 
 {
  HandlerMethod methodHandler = (HandlerMethod) handler;
  log.debug("END EXECUTION method {} request: {}", methodHandler.getMethod().getName(), request.getRequestURI());
  }
 

 @Override
 public boolean preHandle(HttpServletRequest request,
  HttpServletResponse response, Object handler) throws Exception 
  {

  } catch (IllegalArgumentException e) 
  {
   log.warn("Prehandle", e);
   return true;
  } finally 
  {
   HandlerMethod methodHandler = (HandlerMethod) handler;
   log.debug("START EXECUTION method {} request: {}", methodHandler.getMethod().getName(), request.getRequestURI());
  }
  return true;
}

For authentication of web pages you would use a servlet filter which acts at weblayer. For security stuff in your business layer or logging/bugtracing (a.k.a. independent of the web layer) you would use an Interceptor.