Link to home
Start Free TrialLog in
Avatar of srikotesh
srikotesh

asked on

how to use lamda expression while iterating for loop with map or list in java

Hi Experts,

Can some suggest me how to use lamda expression while iterating map or list in for loop.

give some difference with old java version and what we achieved if we use with lamda expression.

Thanks,
Avatar of CPColin
CPColin
Flag of United States of America image

It depends on what you're trying to do. It may be better if you posted some code in the old style and let us translate it to the new style, if possible.
Avatar of srikotesh
srikotesh

ASKER

List<Integer > l= new Arraylist<>();
l.add(123);
l.add(456);
l.add(789);

for (Integer val :l){
system. out.printing(val);
}

how to use lambda expression in this scenario.
This will pass each element in the list to System.out.println():

l.stream().forEach(System.out::println);

Open in new window

Object data= dao.getvalues();//getting values from db
for (Object obj:data){
Object[] row = (Object [])obj;
final Employee employee = new Employee();
employee.getId((int)row[0];
employee.Genome((String)row[1]);
}
return employee;

how to use lambda expression here
That code won't compile. Your data variable isn't an array and doesn't implement Iterable, so you can't use it in an enhanced for loop. Your employee variable goes out of scope before your return statement.
List<Object> taskActionDetails = Dao.getTaskAction(input.getid(), input.getCustomer());//getting the values from database.
        List<Integer> reqClassificationActionIds = Collections.emptyList();
        if(!taskActionDetails.isEmpty()) {
            reqClassificationActionIds = new LinkedList<>();
            // TODO:lamda
            for (Object taskAction : taskActionDetails) {
                int actionId = (int) taskAction;
                reqClassificationActionIds.add(actionId);
                
            }
        }

Open in new window

how to use lamda in the above code
This will do it:

List<Integer> reqClassificationActionIds = taskActionDetails.stream()
   .map(object -> (Integer)object)
   .collect(Collectors.toList());

Open in new window


If you really want a LinkedList, use this:

List<Integer> reqClassificationActionIds = taskActionDetails.stream()
   .map(object -> (Integer)object)
   .collect(Collectors.toCollection(LinkedList::new));

Open in new window

Hi CPColin,

I am getting the below error:
Exception in thread "main" java.lang.ClassCastException: Employee cannot be cast to java.lang.Integer
      at ListComparision.lambda$0(ListComparision.java:14)
      at ListComparision$$Lambda$1/424058530.apply(Unknown Source)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374)
      at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:512)
      at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
      at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
      at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
      at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
      at ListComparision.main(ListComparision.java:15)
Hi CPColin,

i am getting the following error:
Exception in thread "main" java.lang.ClassCastException: Employee cannot be cast to java.lang.Integer
      at ListComparision.lambda$0(ListComparision.java:14)
      at ListComparision$$Lambda$1/424058530.apply(Unknown Source)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374)
      at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:512)
      at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
      at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
      at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
      at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
      at ListComparision.main(ListComparision.java:15)


i will explain my code
List<Object> taskActionDetails = Dao.getTaskAction(input.getid(), input.getCustomer());//getting the values from  database it is of type Object
//now i have created one list of type integer.
        List<Integer> reqClassificationActionIds = Collections.emptyList();
        if(!taskActionDetails.isEmpty()) {
//taskActionDetails have values then only i am creating list object
            reqClassificationActionIds = new LinkedList<>();
            // TODO:lamda
//here i am iterate taskaction details values and converting object into integer type.
            for (Object taskAction : taskActionDetails) {
                int actionId = (int) taskAction;
//one i converted then i am adding new list of type integer
                reqClassificationActionIds.add(actionId);
                
            }
        }

Open in new window

Does your original code work? I would expect it to throw the same exception, if that taskActionDetails object contains anything other than Integer objects.
my code will work.
I have already done ny task.
I want to use lambda expression.
I would expect line 10 in your above code snippet to throw the same exception. Either the list is full of Integer objects or it's full of Employee objects. Could you post the entirety of the code that's working properly?
what is the difference b/w  
::     and   ->  in lamda expressions

public class ListComparision {

	public static List<Person> getEmpDetails(){
		
		
		 List<Person> phpProgrammers = new ArrayList<>();
		 phpProgrammers.add(new Person("Jarrod", "Pace", "PHP programmer", "male", 34, 1550));
		 phpProgrammers.add(new Person("Clarette", "Cicely", "PHP programmer", "female", 23, 1200));
		 phpProgrammers.add(new Person("Victor", "Channing", "PHP programmer", "male", 32, 1600));
		 phpProgrammers.add(new Person("Tori", "Sheryl", "PHP programmer", "female", 21, 1000));
		 phpProgrammers.forEach((p) -> System.out.printf("%s %s; ", p.getFirstName(), p.getLastName()));
		 return phpProgrammers;
	}  
	
	public static void main(String args[]){
		getEmpDetails();
	}
}

Open in new window

You have to use the -> operator when you're not passing the whole object or when you're calling multiple methods on the object. You can use :: when the whole object will be passed to that method.

In the code you posted above, Person.getFirstName() and Person.getLastName() are both being called and then passed to System.out.printf(). There's too much stuff going on to be able to use ::.

If you just wanted to print all the last names, you could do something like this:

phpProgrammers.stream()
   .map(Person::getLastName)
   .forEach(System.out::println);

Open in new window


Since each step is operating on the whole object at once, :: works.
instead of printing in system.out.println
i want to store these first name and last name in some list .
is it possible ?

In real time scenarios
i will hit the database and get the list of records
each record i want to insert into list .
is there any way we can use lamda expression here?
Post some code, preferably some that compiles, and I'll see where lambda expressions could be used.
HI CPCOLIN,

 List<Object> counterInterfaces = dataFromDAO.getCounterInterfaceDetails(childCiDetails);
        List<CounterInterfacesDTO> counterInterfaces = Collections.emptyList();
        if(!counterInterfaces.isEmpty()) {
            counterInterfaces = new LinkedList<>();
            for (Object object : counterInterfaces) {
                Object[] row = (Object[]) object;
                final CounterInterfacesDTO counterInterfacesDTO = new counterInterfacesDTO();
                counterInterfacesDTO.setName((String) row[0]);
                counterInterfacesDTO.setSpeed((String) row[1]);
                counterInterfaces.add(counterInterfacesDTO);
            }
        }

Open in new window


HOW TO USE LAMDA IN THIS FOR LOOP
ASKER CERTIFIED SOLUTION
Avatar of CPColin
CPColin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi CPColin,

The above code is working fine with lamda expression.
while returning list object outside for loop it is not accepting.
my method has to return list object right
I don't understand what you mean.
public List<CounterInterfacesDTO> getDetailsInfo(){
		 
List<Object> objects = dataFromDAO.getCounterInterfaceDetails(childCiDetails);
      List<CounterInterfacesDTO> counterInterfaces = new ArrayList<>();
      
      objects.stream()
         .map(object -> (Object[])object)
         .forEach(row ->
         {
            final CounterInterfacesDTO counterInterfacesDTO = new CounterInterfacesDTO();
            counterInterfacesDTO.setName((String) row[0]);
            counterInterfacesDTO.setSpeed((String) row[1]);
            counterInterfaces.add(counterInterfacesDTO);
         });
		return counterInterfaces //here is the problem i am unable return the list out side of forloop
		
}

Open in new window

What error are you getting?
if i declare list object inside for loop
and return list object inside itself no error.
method level declaration is not possible like that i got.

second scenario:
let suppose i have that list now i want  to set to some other object

counters.setCounterInterfaces(counterInterfaces);//in this case also i am not able to set that list object

if u need still clarity means i will post the error later i dont have code right now
Yeah, the exact error will help.
excellent
Hi CpColin,
the below code at one place iam getting the error like local variable with in the scope must be declared as final.
how to resolve it.
public List<CounterInterfacesDTO> getDetailsInfo(){		 
List<Object> objects = dataFromDAO.getCounterInterfaceDetails(childCiDetails);
      List<CounterInterfacesDTO> counterInterfaces = new ArrayList<>();      
      objects.stream()
         .map(object -> (Object[])object)
         .forEach(row ->
         {
            final CounterInterfacesDTO counterInterfacesDTO = new CounterInterfacesDTO();
            counterInterfacesDTO.setName((String) row[0]);
            counterInterfacesDTO.setSpeed((String) row[1]);
            counterInterfaces.add(counterInterfacesDTO); //here i am getting the error like local variable with in the scope must be declared as final
         });
		 return counterInterfaces;
		
}

Open in new window

First off, why did you close this question if you weren't done with it? Second, the first line of the method you just posted does not compile. It probably refers to a member variable. When I fixed that error, the rest of the method compiled fine. I don't know if my version of Eclipse is treating the code differently than yours is, or what. You could try writing the code like this:

      List<CounterInterfacesDTO> counterInterfaces = objects.stream()
         .map(object -> (Object[])object)
         .map(row ->
         {
            final CounterInterfacesDTO counterInterfacesDTO = new CounterInterfacesDTO();
            counterInterfacesDTO.setName((String) row[0]);
            counterInterfacesDTO.setSpeed((String) row[1]);
            return counterInterfacesDTO;
         })
         .collect(Collectors.toList());

Open in new window


Note that you're not really gaining anything by writing the code this way. To my eye, the above statement is no clearer than a standard for loop would have been.