java‎ > ‎

java2

FAQ
Think of the questions your customers ask most frequently and write them here along with the answers.



A:
Here are two methods that allow you to remove duplicates in an 
ArrayList. removeDuplicate does not maintain the order where asremoveDuplicateWithOrder maintains the order with some performance overhead.
  1. The removeDuplicate Method:

    /** List order not maintained **/

    public static void removeDuplicate(ArrayList arlList)
    {
    HashSet h = new HashSet(arlList);
    arlList.clear();
    arlList.addAll(h);
    }
  2. The removeDuplicateWithOrder Method:

    /** List order maintained **/

    public static void removeDuplicateWithOrder(ArrayList arlList)
    {
    Set set = new HashSet();
    List newList = new ArrayList();
    for (Iterator iter = arlList.iterator();iter.hasNext(); ) {
    Object element = iter.next();
    if (set.add(element))
    newList.add(element);
    }
    arlList.clear();
    arlList.addAll(newList);
    }



A: Creating and deploying war file from eclipse to tomcat or any web container is some time pain full. One of the easy way to do this is by creating Ant script to perform this task.

Step 1: Create a build.xml file and put it in web content folder of your project.

Step 2: Copy and paste following script to your file

<?xml version="1.0" encoding="ISO-8859-1"?>
<project name="Deploy From Eclipse to Tomcat" basedir=".">
<property name="warfile" value="Day Parser"/>
<target name="unpack">
<unwar src="${warfile}.war" dest="${warfile}" />
</target>
<target name="create">
<war destfile="${warfile}.war" webxml="WebContent/WEB-INF/web.xml" update="true">
<classes dir="build\classes"/>
<fileset dir="WebContent">
<exclude name="WEB-INF/web.xml"/>
</fileset>
</war>
</target>
<target name="copy">
<copy todir="path to web apps folder of tomcat" overwrite="true">
<fileset dir=".">
<include name="*.war"/>
</fileset>
</copy>
</target>
<target name="deploy">
<antcall target="create"/>
<antcall target="copy"/>
</target>
</project>

Step 3: In eclipse go to Window -> Show View - > Ant  and click on ant

Step 4: Drap and drop your build.xml to Ant View in explorer.

Step 5: Double click on deploy every time you make some changes in project and want to deploy.

Step 6: Please note that you don't have to restart the server every time you make changes in jsp or java file. Just delete exploded war file from webbapps of tomcat.

A: Recently came across a problem where I wanted to have dates from Starting of week to end of week if I have any random date.

Following method will return all dates of weeks.

private String[] getAllWeekDays(String year,String month,String day){
        String[] allWeekDays = new String[7];
        String dayNames[] = new DateFormatSymbols().getWeekdays();
          GregorianCalendar cal = new GregorianCalendar();
          cal.clear();
        

          cal.set(Calendar.YEAR, Integer.parseInt(year));
          //-1 because array month start from index 0
          cal.set(Calendar.MONTH, Integer.parseInt(month)-1);
          cal.set(Calendar.DATE, Integer.parseInt(day));
       
         Calendar startDate = (Calendar)cal.clone();
         Calendar endDate = (Calendar)cal.clone();     
         int dayOfWeek = startDate.get(Calendar.DAY_OF_WEEK);


         //Enable it if you want previous week dates 
         /*while (dayOfWeek  != Calendar.SUNDAY) {
           startDate.add(Calendar.DATE, -1);
           dayOfWeek = startDate.get(Calendar.DAY_OF_WEEK);
         }*/

         while (dayOfWeek != Calendar.MONDAY) {
           startDate.add(Calendar.DATE, -1);
           dayOfWeek = startDate.get(Calendar.DAY_OF_WEEK);
         }

         // end date , decrement until the first sunday
         dayOfWeek = endDate.get(Calendar.DAY_OF_WEEK);
         while (dayOfWeek  != Calendar.SUNDAY) {
           endDate.add(Calendar.DATE, +1);
           dayOfWeek = endDate.get(Calendar.DAY_OF_WEEK);
         
         }
          System.out.println("Today is"+ dayNames[cal.get(Calendar.DAY_OF_WEEK)]);
          
          //to get next date
          int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
           SimpleDateFormat fomate = new SimpleDateFormat("MM/dd/yyyy");
          System.out.println(fomate.format(cal.getTime().getTime()));
          this.startDate=fomate.format(startDate.getTime().getTime());
          this.endDate=fomate.format(endDate.getTime().getTime());
          System.out.println("All dates Are");
          Date tempDate = startDate.getTime();
          for(int i=0;i<7;i++){          
              System.out.println(fomate.format(tempDate));
              allWeekDays[i]=fomate.format(tempDate);
              tempDate.setTime(tempDate.getTime()+MILLIS_IN_DAY);
          }
        
        return allWeekDays;
        
    }

A: 

int getNumberOfDaysInMonth(String year,String month){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, Integer.parseInt(year));
          //-1 because array month start from index 0
        calendar.set(Calendar.MONTH, Integer.parseInt(month)-1);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        
    }

A: 
//You can remove generics to sort even String. Also You can sort based on object
//Only have to change logic in compare method.

public static Map<String, Integer> getSortedMapbyValue(Map<String, Integer> map){
        List<Integer> listForSort = null;
        Map<String,Integer>  sortedList= new LinkedHashMap<String, Integer>();
        listForSort =new LinkedList(map.entrySet());
       Collections.sort(listForSort, new Comparator() {
             public int compare(Object value1,Object value2) {
//Sort in decending order  change to > for acesnding order.               
                 if(((Map.Entry<String, Integer>)value1).getValue()<((Map.Entry<String, Integer>)value2).getValue()){
                     return 1;
                 }
                 else return 0;
            }
             
       });
       
       Iterator itret =listForSort.iterator();     
       while(itret.hasNext()){
             Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>)itret.next();
            sortedList.put(entry.getKey(), entry.getValue());
      } 

       return sortedList;
       
    }

A: 
//Can be done using pass by reference no need to return any thing
//URLType is a custom object
//This is used to sort in decending order, for acending order only one line is required

public static ArrayList<URLType> getSortedArray(ArrayList<URLType> input)
{
ArrayList<URLType> allURLType = input;
         Collections.sort(allURLType, new Comparator(){             
                public int compare(Object o1, Object o2) {
                    URLType p1 = (URLType) o1;
                    URLType p2 = (URLType) o2;
                    if(p1.getTotalNumberOfRequest()<p2.getTotalNumberOfRequest())
                        return 1;
                    else
                        return 0;
                   //return //p1.getTotalNumberOfRequest().compareTo(p2.getTotalNumberOfRequest());
                }     
            });
return allURLType;
}
Comments