Iterate List in java 8 and invoke another function while iteration

Viewed 5219

I am new to java 8.

me want to use java8 and want to convert below to java8.

List<Model> listModel;
for (Model model : listModel) 
        {
            try
            {
                new UpDateData().bankData(model.getCust_id(), model.getBank_id(), model.getDate());
            }
            catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }

        }

Model class::

public class Model 
{
    private  int cust_id;
    private  int bank_id;
    private  String date;
    //setter and getter
}

My question How me can apply java 8 features on above list, me want to iterate and call teh another function.

2 Answers

you could just use a forEach:

listModel.forEach(model -> {
    try {
        new UpDateData().bankData(model.getCust_id(), model.getBank_id(), model.getDate());
    } catch(){
         .... handle
    }
})

The forEach is used in java 8 for iteration.You can loop over all elements using Iterable.forEach() method.

List<String> words = new ArrayList<>(Arrays.asList("the", "this", 
"that", "there"));
alphabets.forEach(s -> { System.out.println(s) }); //using lamda 

The List<> is the iteratable type, so you can directly use forEach on list.This is known as internal iteration as compared to old external iteration. This is automatically converted to external iteration by java. Curly braces are optional in lambda if there is only one statement else mandatory. You can use filter on iterators as compared to old if blocks in loops.

alphabets.stream()
     .filter(s -> s.startsWith("the"))
     .forEach(System.out::println);
alphabets.stream()
     .filter(s -> s.length() > 3)
     .forEach(System.out::println);

The above syntax use method reference for printing the elements.

https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html

Related