Tuesday, 9 February 2016

Collections

Q- what is serilization?

ans-

Q-what is syncronization? 

ans-

How To Convert ArrayList to String Array In Java

 

import java.util.ArrayList;
import java.util.List;
public class Java4s {
public static void main(String args[]){
    List al = new ArrayList<String>();
    al.add("One");
    al.add("Two");
    al.add("Three");
    al.add("Four");
    al.add("Five");
    String[] stringArrayObject = new String[al.size()];
    al.toArray(stringArrayObject);// we converted List data into String array
    for(String temp : stringArrayObject)
    System.out.println(temp);
}
}

 

How to Remove Duplicate Values From Java List/ArrayList?

 

RemDupFromList.java

Explanation

  • Take your normal List object
  • Pass that List li object to Set [Line number 22]  => So finally we have Set object in our hand, just pass this current Set object as argument to ArrayList, so we got new List object li2 without duplicate
  • But if you would like to preserve the order of data use LinkedHashSet rather HashS
  •  

    How to Sort Arrays in Java, Arrays Sorting In Java

    SortArray.java

    Output

    Countries : Australia
    Countries : India
    Countries : Lundon
    Countries : Malaysia
    Countries : United States

    How to sort ArrayList in java, Sorting java Collections

    SortCollection.java


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26





    package java4s;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;
    public class SortCollection {
    public static void main(String... args)
    {
        List li = new ArrayList();
        li.add("India");
        li.add("United States");
        li.add("Malaysia");
        li.add("Australia");
        li.add("Lundon");
        Collections.sort(li);
    for(String temp: li)

    How to Convert a List to a Set in Java with Example


    import java.util.Arrays;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;

    /**
     * Java program example to convert a List to a Set in Java./
     * It also shows way to copy one collection to another
     * Collection in Java

     * You can copy data from List to Set using addAll()
     * method or you can create copy of collection
     * by passing another Collection like ArrayList
     * to its constructor while creating.
     *
     * @author Javin Paul
     */

    public class ListtoSet{
     
        public static void main(String args[]) throws InterruptedException{            
     
         
         List<String> teams = Arrays.asList("India" , "Australia" , "England", "Pakistan");
       
         System.out.println("Original List: " + teams);
       
         // copying contents from List to Set in Java,
         // remember this will remove duplicates from
         // collection because List supports duplicates but


         //Set does not support duplicates in Java
       
         Set<String> cricketTeams = new HashSet<String>(teams);
       
         System.out.println("Copy collection :" + cricketTeams);
       
         
        }  
     
    }

    Output:
    Original List: [India, Australia, England, Pakistan]
    Copy collection :[Pakistan, England, Australia, India]

    Sort ArrayList in Ascending and Descending order 

    Code Example of Sorting ArrayList in Java

    Here is complete code example of sorting an arraylist in java on both natural and custom order by using Custom comparator.
    package test;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    public class ArrayListSortingExample {
       private static class SmartPhone implements Comparable {
            private String brand;
            private String model;
            private int price;
            public SmartPhone(String brand, String model, int price){
                this.brand = brand;
                this.model = model;
                this.price = price;
            }
          
            @Override
            public int compareTo(SmartPhone sp) {
                return this.brand.compareTo(sp.brand);
            }
            @Override
            public String toString() {
                return "SmartPhone{" + "brand=" + brand + ", model=" + model + ", price=" + price + '}';
            }
          
        }
      
        private static class PriceComparator implements Comparator{
            @Override
            public int compare(SmartPhone sp1, SmartPhone sp2) {
                return (sp1.price < sp2.price ) ? -1: (sp1.price > sp2.price) ? 1:0 ;
            }
          
        }
        public static void main(String... args) {
          
            //creating objects for arraylist sorting example
            SmartPhone apple = new SmartPhone("Apple", "IPhone4S",1000);
            SmartPhone nokia = new SmartPhone("Nokia", "Lumia 800",600);
            SmartPhone samsung = new SmartPhone("Samsung", "Galaxy Ace",800);
            SmartPhone lg = new SmartPhone("LG", "Optimus",500);
          
            //creating Arraylist for sorting example
            ArrayList smartPhones = new ArrayList();
          
            //storing objects into ArrayList for sorting
            smartPhones.add(apple);
            smartPhones.add(nokia);
            smartPhones.add(samsung);
            smartPhones.add(lg);
          
            //Sorting Arraylist in Java on natural order of object
            Collections.sort(smartPhones);
          
            //print sorted arraylist on natural order
            System.out.println(smartPhones);
          
            //Sorting Arraylist in Java on custom order defined by Comparator
            Collections.sort(smartPhones,new PriceComparator());
          
            //print sorted arraylist on custom order
            System.out.println(smartPhones);
        
        }
    }
    Output:
    [SmartPhone{brand=Apple, model=IPhone4S, price=1000}, SmartPhone{brand=LG, model=Optimus, price=500}, SmartPhone{brand=Nokia, model=Lumia 800, price=600}, SmartPhone{brand=Samsung, model=Galaxy Ace, price=800}]
    [SmartPhone{brand=LG, model=Optimus, price=500}, SmartPhone{brand=Nokia, model=Lumia 800, price=600}, SmartPhone{brand=Samsung, model=Galaxy Ace, price=800}, SmartPhone{brand=Apple, model=IPhone4S, price=1000}]

    How to sort ArrayList in Descending Order in Java

    ArrayList can also be sorted in descending or reverse order by using Collections.reverseOrder() and Collection.reverseOrder(Comparator cmp)
    //sorting ArrayList in descending or reverse order in Java
    List unsortedList = Arrays.asList("abc", "bcd", "ade", "cde");
    Collections.sort(unsortedList, Collections.reverseOrder());
    System.out.println("Arraylist in descending order: " + unsortedList);
    Output:
    ArrayList before sorting in reverse order: [abc, bcd, ade, cde]
    Arraylist in descending order: [cde, bcd, ade, abc]

    How to sort ArrayList of String  in Case insensitive Order


    ArrayList  of String can also be sorted with case insensitive comparison. String class defines a convenient case insensitive comparator which can be accessed directly like String.CASE_INSENSITIVE_ORDER . if you pass this comparator to ArrayList.sort() which contains String then those will be sorted accordingly. Here is an example of sorting arraylist in case insensitive order:
    //sorting ArrayList on case insensitive order of String
    unsortedList = Arrays.asList("abc", "bcd", "ABC", "BCD");
    System.out.println("ArrayList before case insensitive sort: " + unsortedList);
                 
    Collections.sort(unsortedList, String.CASE_INSENSITIVE_ORDER);
    System.out.println("ArrayList after case insensitive sort: " + unsortedList);
    Output:
    ArrayList before case insensitive sort: [abc, bcd, ABC, BCD]
    ArrayList after case insensitive sort: [abc, ABC, bcd, BCD]


    Serializable vs Externalization in Java

    difference between Java Serialization vs Externalization in Javahere are some more differences between Serializable and Externalizable interface in Java:
    1. In case of Serializable, default serialization process is used. while in case of Externalizable custom Serialization process is used which is implemented by application.
    2. JVM gives call back to readExternel() and writeExternal() of java.io.Externalizalbe interface for restoring and writing objects into persistence.
    3. Externalizable interface provides complete control of serialization process to application.
    4. readExternal() and writeExternal() supersede any specific implementation of writeObject and readObject methods.
    Though Externalizable provides complete control, it also presents challenges to serialize super type state and take care of default values in case of transient variable and static variables in Java. If used correctly Externalizable interface can improve performance of serialization process.

    Important points about transient keyword in java

    Here are few important points about transient variables in java which I found, let me know if you have some more which I missed out here and I will include here.
    1) Transient keyword can only be applied to fields or member variable. Applying it to method or local variable is compilation error.
    2) Another important point is that you can declare an variable static and transient at same time and java compiler doesn't complain but doing that doesn't make any sense because transient is to instruct "do not save this field" and static variables are not saved anyway during serialization.
    3) In similar way you can apply transient and final keyword together to a variable compiler will not complain but you will face another problem of reinitializing a final variable during deserialization.
    4) Transient variable in java is not persisted or saved when an object gets serialized.

    Example of transient variable in java

    To understand the concept of transient variables let see a live example in java.
    public class Stock {
        private transient Logger logger = Logger.getLogger(Stock.class); //will not serialized
        private String symbol; //will be serialized
        private BigInteger price; //serialized
        private long quantity; //serialized
    }


    28) How to make a collection thread safe?
    ans-
    Use below methods:
    • Collections.synchronizedList(list);
    • Collections.synchronizedSet(set);
    • Collections.synchronizedMap(map);
    Above methods take collection as parameter and return same type of collection which are synchronized and thread safe.

No comments:

Post a Comment