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,
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,
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.
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.
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);
ASKER
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)ro w[1]);
}
return employee;
how to use lambda expression here
for (Object obj:data){
Object[] row = (Object [])obj;
final Employee employee = new Employee();
employee.getId((int)row[0]
employee.Genome((String)ro
}
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.
ASKER
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);
}
}
ASKER
how to use lamda in the above code
This will do it:
If you really want a LinkedList, use this:
List<Integer> reqClassificationActionIds = taskActionDetails.stream()
.map(object -> (Integer)object)
.collect(Collectors.toList());
If you really want a LinkedList, use this:
List<Integer> reqClassificationActionIds = taskActionDetails.stream()
.map(object -> (Integer)object)
.collect(Collectors.toCollection(LinkedList::new));
ASKER
Hi CPColin,
I am getting the below error:
Exception in thread "main" java.lang.ClassCastExcepti on: Employee cannot be cast to java.lang.Integer
at ListComparision.lambda$0(L istCompari sion.java: 14)
at ListComparision$$Lambda$1/ 424058530. apply(Unkn own Source)
at java.util.stream.Reference Pipeline$3 $1.accept( ReferenceP ipeline.ja va:193)
at java.util.ArrayList$ArrayL istSpliter ator.forEa chRemainin g(ArrayLis t.java:137 4)
at java.util.stream.AbstractP ipeline.co pyInto(Abs tractPipel ine.java:5 12)
at java.util.stream.AbstractP ipeline.wr apAndCopyI nto(Abstra ctPipeline .java:502)
at java.util.stream.ReduceOps $ReduceOp. evaluateSe quential(R educeOps.j ava:708)
at java.util.stream.AbstractP ipeline.ev aluate(Abs tractPipel ine.java:2 34)
at java.util.stream.Reference Pipeline.c ollect(Ref erencePipe line.java: 499)
at ListComparision.main(ListC omparision .java:15)
I am getting the below error:
Exception in thread "main" java.lang.ClassCastExcepti
at ListComparision.lambda$0(L
at ListComparision$$Lambda$1/
at java.util.stream.Reference
at java.util.ArrayList$ArrayL
at java.util.stream.AbstractP
at java.util.stream.AbstractP
at java.util.stream.ReduceOps
at java.util.stream.AbstractP
at java.util.stream.Reference
at ListComparision.main(ListC
ASKER
Hi CPColin,
i am getting the following error:
Exception in thread "main" java.lang.ClassCastExcepti on: Employee cannot be cast to java.lang.Integer
at ListComparision.lambda$0(L istCompari sion.java: 14)
at ListComparision$$Lambda$1/ 424058530. apply(Unkn own Source)
at java.util.stream.Reference Pipeline$3 $1.accept( ReferenceP ipeline.ja va:193)
at java.util.ArrayList$ArrayL istSpliter ator.forEa chRemainin g(ArrayLis t.java:137 4)
at java.util.stream.AbstractP ipeline.co pyInto(Abs tractPipel ine.java:5 12)
at java.util.stream.AbstractP ipeline.wr apAndCopyI nto(Abstra ctPipeline .java:502)
at java.util.stream.ReduceOps $ReduceOp. evaluateSe quential(R educeOps.j ava:708)
at java.util.stream.AbstractP ipeline.ev aluate(Abs tractPipel ine.java:2 34)
at java.util.stream.Reference Pipeline.c ollect(Ref erencePipe line.java: 499)
at ListComparision.main(ListC omparision .java:15)
i will explain my code
i am getting the following error:
Exception in thread "main" java.lang.ClassCastExcepti
at ListComparision.lambda$0(L
at ListComparision$$Lambda$1/
at java.util.stream.Reference
at java.util.ArrayList$ArrayL
at java.util.stream.AbstractP
at java.util.stream.AbstractP
at java.util.stream.ReduceOps
at java.util.stream.AbstractP
at java.util.stream.Reference
at ListComparision.main(ListC
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);
}
}
Does your original code work? I would expect it to throw the same exception, if that taskActionDetails object contains anything other than Integer objects.
ASKER
my code will work.
I have already done ny task.
I want to use lambda expression.
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?
ASKER
what is the difference b/w
:: and -> in lamda expressions
:: 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();
}
}
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:
Since each step is operating on the whole object at once, :: works.
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);
Since each step is operating on the whole object at once, :: works.
ASKER
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?
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.
ASKER
HI CPCOLIN,
HOW TO USE LAMDA IN THIS FOR LOOP
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);
}
}
HOW TO USE LAMDA IN THIS FOR LOOP
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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
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.
ASKER
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
}
What error are you getting?
ASKER
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.setCounterInterfa ces(counte rInterface s);//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
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.setCounterInterfa
if u need still clarity means i will post the error later i dont have code right now
Yeah, the exact error will help.
ASKER
excellent
ASKER
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.
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;
}
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:
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.
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());
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.