Example of mapToLong in Java 8

UPDATED: 08 October 2015

LongStream mapToLong(ToLongFunction<? super T> mapper)
Returns a LongStream consisting of the results of applying the given function to the elements of this stream.

Source code (Company.java)
public class Company {
    private Long id;
    private String CompanyName;
 
 public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCompanyName() {
        return CompanyName;
    }

    public void setCompanyName(String CompanyName) {
        this.CompanyName = CompanyName;
    }
}

Source code
import java.util.ArrayList;
import java.util.List;

public class MapToLongExample {
    public static void main(String[] args) {
        /* Create an object of `Company` and set values */
        Company companyApple = new Company();
        companyApple.setId(1L);
        companyApple.setCompanyName("Apple");
        
        Company companySamsung = new Company();
        companySamsung.setId(2L);
        companySamsung.setCompanyName("Samsung");
       
        /**
         * - Create `List` of `Company`
         * - Add `companyApple` and `companySamsung` to List.
         */
        List<Company> mobileCompanies=  new ArrayList<>();
        mobileCompanies.add(companyApple);
        mobileCompanies.add(companySamsung);
        
        /**
         * JavaDoc: `mapToLong` method
         * Returns a LongStream consisting of the results of applying the given function to the elements of this stream.
         * 
         * Explanation: `.mapToLong(Company::getId)` / `.mapToLong(company -> company.getId())`
         * In this operation we are calling method `getId()` on each object of `Company` in List.
         * That returns the `LongStream` of value(Id) of all object in List.
         * At last print company `Ids`.
         */
        mobileCompanies.stream()
                       .mapToLong(Company::getId)
                       .forEach(companyID ->{
                           System.out.println(companyID);
                       });
    }
}

Explanation: .mapToLong(Company::getId) / .mapToLong(company -> company.getId())
In this operation we are calling method getId() on each object of Company in List. That returns the LongStream of value(Id) of all object in List. At last print company Ids.


Output
1
2
Other References:
Example of mapToDouble in Java 8
Example of mapToInt in Java 8

0 comments :