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,
LVL 2
srikoteshAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CPColinSenior Java ArchitectCommented:
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.
srikoteshAuthor Commented:
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.
CPColinSenior Java ArchitectCommented:
This will pass each element in the list to System.out.println():

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

Open in new window

CompTIA Network+

Prepare for the CompTIA Network+ exam by learning how to troubleshoot, configure, and manage both wired and wireless networks.

srikoteshAuthor Commented:
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
CPColinSenior Java ArchitectCommented:
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.
srikoteshAuthor Commented:
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

srikoteshAuthor Commented:
how to use lamda in the above code
CPColinSenior Java ArchitectCommented:
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

srikoteshAuthor Commented:
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)
srikoteshAuthor Commented:
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

CPColinSenior Java ArchitectCommented:
Does your original code work? I would expect it to throw the same exception, if that taskActionDetails object contains anything other than Integer objects.
srikoteshAuthor Commented:
my code will work.
I have already done ny task.
I want to use lambda expression.
CPColinSenior Java ArchitectCommented:
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?
srikoteshAuthor Commented:
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

CPColinSenior Java ArchitectCommented:
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.
srikoteshAuthor Commented:
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?
CPColinSenior Java ArchitectCommented:
Post some code, preferably some that compiles, and I'll see where lambda expressions could be used.
srikoteshAuthor Commented:
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
CPColinSenior Java ArchitectCommented:
That code wouldn't have compiled, since you used the same variable name more than once. Here's what it looks like using streams:

      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);
         });

Open in new window


As you can see, it doesn't make the code much more clear, so it might not be worth it.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
srikoteshAuthor Commented:
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
CPColinSenior Java ArchitectCommented:
I don't understand what you mean.
srikoteshAuthor Commented:
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

CPColinSenior Java ArchitectCommented:
What error are you getting?
srikoteshAuthor Commented:
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
CPColinSenior Java ArchitectCommented:
Yeah, the exact error will help.
srikoteshAuthor Commented:
excellent
srikoteshAuthor Commented:
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

CPColinSenior Java ArchitectCommented:
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.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.