Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert list of object to another list object using streams?

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;
    }
}
like image 615
Learn Hadoop Avatar asked Dec 13 '17 14:12

Learn Hadoop


People also ask

How do I convert one object to another object in Java 8?

In Java 8, we have the ability to convert an object to another type using a map() method of Stream object with a lambda expression. The map() method is an intermediate operation in a stream object, so we need a terminal method to complete the stream.

Which method is used to convert Stream to list?

The Collector class is used to collect the elements of the Stream into a collection. This class has the toList() method, which converts the Stream to a List.


1 Answers

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()));
like image 165
fxrbfg Avatar answered Oct 21 '22 16:10

fxrbfg