The below code snippet, has been implemented without lambda expressions.
How to implement the same functionality using lambda expressions?
public class Java8EmpTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Emp> empInList = Arrays.asList(new Emp(1, 100), new Emp(2, 200), new Emp(3, 300));
List<Emp> afterSalayHikeInJava7 = new ArrayList<>();
// old way
for (Emp emp : empInList) {
afterSalayHikeInJava7.add(new Emp(emp.getId(), emp.getSalary() * 100));
}
afterSalayHikeInJava7.stream()
.forEach(s -> System.out.println("Id :" + s.getId() + " Salary :" + s.getSalary()));
}
}
class Emp {
private int id;
private int salary;
public int getId() {
return id;
}
Emp(int id, int salary) {
this.id = id;
this.salary = salary;
}
public int getSalary() {
return salary;
}
}
Simple use map()
method in stream api and collect results:
List<Emp> employe = Arrays.asList(new Emp(1, 100), new Emp(2, 200), new Emp(3, 300));
List<Emp> employeRise = employe.stream()
.map(emp -> new Emp(emp.getId(), emp.getSalary * 100))
.collect(Collectors.toList());
employeRise.stream()
.forEach(s -> System.out.println("Id :" + s.getId() + " Salary :" + s.getSalary()));
map()
each Emp
of the input List
to a new Emp
and then collect()
to a List
:
List<Emp> afterSalayHike =
empInList.stream()
.map(emp->new Emp(emp.getId(), emp.getSalary() * 100))
.collect(Collectors.toList());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.