Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print arraylist element?

Tags:

java

how do i print the element "e" in arraylist "list" out?

 ArrayList<Dog> list = new ArrayList<Dog>();
 Dog e = new Dog();
 list.add(e);
 System.out.println(list);
like image 799
ajsie Avatar asked Jan 12 '10 06:01

ajsie


3 Answers

First make sure that Dog class implements the method public String toString() then use

System.out.println(list.get(index))

where index is the position inside the list. Of course since you provide your implementation you can decide how dog prints itself.

like image 196
Jack Avatar answered Oct 17 '22 10:10

Jack


Here is an updated solution for Java8, using lambdas and streams:

System.out.println(list.stream()
                       .map(Object::toString)
                       .collect(Collectors.joining("\n")));

Or, without joining the list into one large string:

list.stream().forEach(System.out::println);
like image 41
AJNeufeld Avatar answered Oct 17 '22 12:10

AJNeufeld


Do you want to print the entire list or you want to iterate through each element of the list? Either way to print anything meaningful your Dog class need to override the toString() method (as mentioned in other answers) from the Object class to return a valid result.

public class Print {
    public static void main(final String[] args) {
        List<Dog> list = new ArrayList<Dog>();
        Dog e = new Dog("Tommy");
        list.add(e);
        list.add(new Dog("tiger"));
        System.out.println(list);
        for(Dog d:list) {
            System.out.println(d);
            // prints [Tommy, tiger]
        }
    }

    private static class Dog {
        private final String name;
        public Dog(final String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return name;
        }
    }
}

The output of this code is:

[Tommy, tiger]  
Tommy  
tiger
like image 12
sateesh Avatar answered Oct 17 '22 10:10

sateesh