Showing posts with label Collections Framework. Show all posts
Showing posts with label Collections Framework. Show all posts

July 16, 2011

Wiring Collections in a Spring bean

0) Setup the Spring framework in the web application by executing the Hello World example at this link

1) Create the interface for the spring bean, ICollections.java, as follows,

package info.icontraining.spring;

public interface ICollections {
   public void printList();
   public void printMap();
}

2) Create a spring bean class, CollectionsExample.java as follows,

package info.icontraining.spring;

import java.util.*;

public class CollectionsExample implements ICollections {

   List list;
   Map map;
 
   public void printList() {
      for(String s: list) {
         System.out.println(s);
      }
   }
 
   public void printMap() {
      for(String s: map.keySet()) {
         System.out.println(s + ": " + map.get(s));
      }
   }
 
   public void setMyList(List list) {
      this.list = list;
   }
 
   public void setMyMap(Map map) {
      this.map = map;
   }
}

3) Add the following configuration for the spring bean in the applicationContext.xml file in WebContent/WEB-INF folder - this configuration injects a List and a Map into the spring bean.

<bean id="listExample" class="info.icontraining.spring.CollectionsExample">
   <property name="myList">
      <list>
         <value>String 1</value>
         <value>String 2</value>
         <value>String 3</value>
      </list>
   </property>
   <property name="myMap">
      <map>
         <entry key="key1" value="value1" />
         <entry key="key2" value="value2" />
         <entry key="key3" value="value3" />
      </map>
   </property>
</bean>

4) Create a JSP, springTest.jsp as follows,

<%@ page  import="org.springframework.context.*,org.springframework.web.context.*,info.icontraining.spring.*"%>
<html>
<body>
View output on Server console
<%
ApplicationContext factory =
  (ApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); ICollections collection = (ICollections)factory.getBean("listExample");
collection.printList();
collection.printMap();
%>

</body>
</html>

5) Test the example with the following URL in the browser,

http://localhost:8080/WebAppName/springTest.jsp

June 12, 2011

Java Collections Framework: Map Example with HashMap and equals() and hashCode() implementation

The HashMap implementation of the Map interface uses hashing to store and find objects. Putting a good implementation of the hashCode() method optimizes searching for objects.

The containsKey() and the containsValue() methods use the equals() method to check for meaningful equality of objects. Classes that have not implemented the equals() methods will not be checked for meaningful equality and will only be checked for referential equality by the containsKey() and the containsValue() methods.

HashMapExample.java

package info.icontraining.collections;

import java.util.*;

public class HashMapExample {

   public static void main(String[] args) {
  
      Map<Customer, Integer> map = new HashMap<Customer, Integer>();

      map.put(new Customer("Dinesh", "Atlanta"), 1);
      map.put(new Customer("Tanvi", "Norcross"), 2);
      map.put(new Customer("Laksh", "Duluth"), 3);
      map.put(new Customer("Dinesh", "Alpharetta"), 4);

      System.out.println("Size of Map = " + map.size());  
      System.out.println(map.containsKey(new Customer("Laksh", "Duluth")));       }
}

Customer.java

package info.icontraining.collections;
 
public class Customer {

   private String customerName;
   private String customerCity;
 
   public Customer(String customerName, String customerCity) {
      this.customerName = customerName;
      this.customerCity = customerCity;
   }
 
   public String getCustomerName() {
      return this.customerName;
   }
 
   public String getCustomerCity() {
      return this.customerCity;
   }
 
   public int hashCode() {
      return customerName.length() + customerCity.length();
   }
 
   public boolean equals(Object c) {
      if ((this.customerName.equals(((Customer)c).customerName)) 
          && (this.customerCity.equals(((Customer)c).customerCity))) {
         return true;
      }
      return false;
   }
}

Java Collections Framework: TreeSet Example with Comparable and Comparator implementation

The TreeSet implementation of the Set interface maintains a sorted collection of unique objects. The custom sort order is determined by implementing either the Comparable interface or the Comparator interface.

In case of the Comparable interface, the class (objects of which will be added to the TreeSet) has to implement the interface.

In case of the Comparator interface. an external class implements the interface. The Comparator allows creating a custom sort order for objects of a 3rd party class.

TreeSet code example with Comparable to compare objects for custom sort order

package info.icontraining.collections;

import java.util.*;

public class TreeSetExample {

   public static void main(String[] args) {
 
      Set customers = new TreeSet();

      customers.add(new Customer("Dinesh", "Atlanta"));      
      customers.add(new Customer("Tanvi", "Norcross"));
      customers.add(new Customer("Laksh", "Duluth"));
  
      for(Customer c: customers) {
         System.out.print(c.getCustomerName() + " | ");
         System.out.println(c.getCustomerCity());      
      }  
     
      customers.add(new Customer("Dinesh", "Alpharetta"));

      System.out.println();

      for(Customer c: customers) {
         System.out.print(c.getCustomerName() + " | ");
         System.out.println(c.getCustomerCity());      
      }    
   }
}

package info.icontraining.collections;

public class Customer implements Comparable {

   private String customerName;
   private String customerCity;
 
   public Customer(String customerName, String customerCity) {
      this.customerName = customerName;
      this.customerCity = customerCity;
   }
 
   public int compareTo(Customer customer) {
      int nameOrder = this.customerName.compareTo(customer.customerName);

      if (nameOrder == 0)
         return this.customerCity.compareTo(customer.customerCity);
  
      return nameOrder;
   }
 
   public String getCustomerName() {
      return this.customerName;
   }
 
   public String getCustomerCity() {
      return this.customerCity;
   }
}

TreeSet code example with Comparator to compare objects for custom sort order

Using the Comparator interface entails creating a new class to implement the interface. The Comparator should be used in the situation where the Customer class is a 3rd party class whose source code is unavailable to us.

package info.icontraining.collections;

import java.util.Comparator;

public class CustomerComparator implements Comparator {

   public int compare(Customer c1, Customer c2) {
      int nameOrder = c1.getCustomerName().compareTo(c2.getCustomerName());
  
      if (nameOrder == 0)
         return c1.getCustomerCity().compareTo(c2.getCustomerCity());
  
      return nameOrder;
   }
}

Also make the following changes to run the example with Comparator instead of Comparable,

1) From the Customer class, remove the implements Comparable

2) In the TreeSetExample class, replace the following line to instantiate the TreeSet

Set<Customer> customers = new TreeSet<Customer>();

with

Set<Customer> customers = new TreeSet<Customer>(new CustomerComparator());

April 4, 2011

Java Collections Framework: PriorityQueue Example

package info.icontraining.collections;

import java.util.*;

public class PriorityQueueExample {

   public static void main(String args[]) {

      Queue<Test> queue = new PriorityQueue<Test>();
  
      queue.offer(new Test(3));
      queue.offer(new Test(1));
      queue.offer(new Test(2));
  
      while (queue.size()!= 0) {
         System.out.println(queue.poll().getPriority());
      }
   }
}

class Test implements Comparable<Test> {
   private int priority;
 
   public Test(int priority) {
      this.priority = priority;
   }

   public int compareTo(Test o) {
      if (this.priority < o.priority)
         return -1;
      else if (this.priority > o.priority)
         return 1;
      return 0;
   }
 
   public int getPriority() {
      return this.priority;
   }
}

Java Collections Framework: List Example


package info.icontraining.collections;

import java.util.*;

public class ListExample {

   public static void main(String[] args) {

      List list = new ArrayList();
  
      list.add("Be");
      list.add("The");
      list.add("Change");
      list.add("You");
      list.add("Wish");
      list.add("Wish");
      list.add("To");
      list.add("See.");
  
      System.out.println("Size: " + list.size());
  
      System.out.println("List Contains \"You\": " + list.contains("You"));
      System.out.println("Index 6: " + list.get(6));
      System.out.println("indexOf \"Change\": " +list.indexOf("Change"));
  
      Iterator iterator = list.iterator();
      for( ; iterator.hasNext(); ) {
         System.out.print(iterator.next() + " ");
      }
  
      System.out.println("toString(): " + list.toString());
  
      list.clear();
      System.out.println("Size after clear(): " + list.size());
   }
}