Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in java,how to iterate list of objects

Tags:

java

iteration

i am having the list myEmpls

List myEmpls = new ArrayList();

In this list i have added used defined objects.

LogConf e = getLogs(el);
    //add it to list
 myEmpls.add(e);

Now how to iterate the list of objects and get the values from this objects. How to do this?

like image 846
ssbecse Avatar asked May 15 '11 08:05

ssbecse


People also ask

Can we iterate object in Java?

An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical term for looping. To use an Iterator, you must import it from the java.util package.

How an iterate object can be used to iterate a list in Java?

By using this iterator object, you can access each element in the collection, one element at a time. Obtain an iterator to the start of the collection by calling the collection's iterator() method. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.

Can you iterate through a list in Java?

Since Java 8, we can use the forEach() method to iterate over the elements of a list. This method is defined in the Iterable interface, and can accept Lambda expressions as a parameter.


2 Answers

You could just google this and you would find tons of solutions.. But here is the code:

for(LogConf element : myEmpls) {
  System.out.println(element.getValue());
}

You should also get used to define the type of the elements in the list:

List<LogConf> myEmpls = new ArrayList<LogConf>();
like image 84
Prine Avatar answered Sep 22 '22 05:09

Prine


I know its been some time since this post was made. You can also use the Iterator.

              List myEmpls = new ArrayList();
              Iterator itr = myEmpls.iterator();

              while(itr.hasNext()) {   
                   LogConf Logobj = (LogConf) itr.next();
                   System.out.println(Logobj.getterName());
              }

Hope this helps someone.

like image 36
ThivankaW Avatar answered Sep 21 '22 05:09

ThivankaW