Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to print a List is Java?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 154
    Comment on it

    There are different ways to print a List, below are some example to print a list using:
    1. For loop
    2. While loop, and
    3. Iterator

    import java.util.Arrays;
    import java.util.Iterator;
    import java.util.List;
    public class printmyList {
         public static void main(String[] args) {
    
        String myArray[] = new String[] { "John", "Bob", "Tom", "Mick" };
    
        // convert array to list
        List<String> myList = Arrays.asList(myArray);
        // for loop
        System.out.println("Using for loop..");
        for (int i = 0; i < myList.size(); i++) {
            System.out.println(myList.get(i));
        }
    
    
        // while loop
        System.out.println("Using while loop..");
        int j = 0;
        while (j < myList.size()) {
            System.out.println(myList.get(j));
            j++;
        }
    
        // iterator loop
        System.out.println("Using Iterator..");
        Iterator<String> iterator = myList.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    
        }
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: