Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 08:37:02 Viewed : 459
To print the names of all departments in an organization using Java 8, you will need a data structure representing the departments. Assuming you have a Department
class, here is an example with output:
javaimport java.util.Arrays;
import java.util.List;
public class Department {
private String name;
public Department(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static void main(String[] args) {
// Sample data
List<Department> departments = Arrays.asList(
new Department("HR"),
new Department("Finance"),
new Department("IT"),
new Department("Marketing")
);
// Print the names of all departments using Java 8 streams
departments.stream()
.map(Department::getName)
.forEach(System.out::println);
}
}
Output:
HR Finance IT Marketing
In this example:
Department
class has an attribute for the department name.main
method with a list of Department
objects.Department::getName
) and print the result using forEach
.