Monday, January 12, 2015

Elements of a List or Array and ListEnumeration to List object in Java



How to fill or replace elements of a List or Array List

package com.java2novice.collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MyListFill
{
public static void main(String a[])
{
        List ll = new ArrayList();
        ll.add("one");
        ll.add("two");
        ll.add("three");
        ll.add("four");
        System.out.println("Original List: "+ll);
        Collections.fill(ll, "Temp_string");
        System.out.println("After fill: "+ll);
    }
}

How to find repeated element cound (frequency) of a given collection

package com.java2novice.collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MyListFrequency
{
public static void main(String a[])
{
        List ll = new ArrayList();
        ll.add("one");
        ll.add("two");
        ll.add("three");
        ll.add("four");
        ll.add("two");
        ll.add("three");
        ll.add("two");
        ll.add("one");
        System.out.println("Actual list: "+ll);
        System.out.println("Frequency of 'one': "+Collections.frequency(ll, "one"));
        System.out.println("Frequency of 'three': "+Collections.frequency(ll, "three"));
        System.out.println("Frequency of 'two': "+Collections.frequency(ll, "two"));
    }
}

How to convert Enumeration to List object

package com.java2novice.collections;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;
public class MyEnumerationToList
{
public static void main(String a[])
{
        Vector vct = new Vector();
        vct.add("one");
        vct.add("two");
        vct.add("three");
        vct.add("four");
        vct.add("five");
        Enumeration enm = vct.elements();
        List ll = Collections.list(enm);
        System.out.println("List elements: "+ll);
    }
}

No comments:

Post a Comment