Practical 2 :- Practical on List Interface
Write a Java program to create List containing list of items of type String and use for-each loop to print the items of the list.
Code
import java.util.ArrayList; import java.util.List; /* Practical 2-1 * Author: Vikram * * Write a Java program to create List containing list of items * of type String and use for-each loop to print the items of the * list. */ public class ListInterfaceExample1 { public static void main(String[] args) { // TODO Auto-generated method stub List<String> mylist=new ArrayList<String>(); mylist.add("Prakash"); mylist.add("Suresh"); mylist.add("Ramesh"); mylist.add("Jayesh"); for(String item: mylist) { System.out.println(item); } } }
Output
Output : Prakash Suresh Ramesh Jayesh
Write a Java program to create List containing list of items and use ListIterator interface to print items present in the list. Also print the list in reverse/ backward `direction.
Code
import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /* * Write a Java program to create List containing list of items * and use List Iterator interface to print items present in the * list. Also print the list in reverse/ backward direction. */ public class ListInterfaceRevFor { public static void main(String[] args) { // TODO Auto-generated method stub List<Integer> numberlist=new ArrayList<Integer>(); //Generating list of 10 numbers for(int i=1;i<=10;i++) numberlist.add(i); // printing the list using iterator Iterator<Integer> itr=numberlist.iterator(); while(itr.hasNext()) { System.out.println(itr.next()); } // printing the list using iterator in reverse order System.out.println("Reverse order"); Collections.reverse(numberlist); Iterator<Integer> itr2=numberlist.iterator(); while(itr2.hasNext()) { System.out.println(itr2.next()); } } }
Output
Output 1 2 3 4 5 6 7 8 9 10 Reverse order 10 9 8 7 6 5 4 3 2 1