default void forEach(Consumer<? super T> action)
Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are relayed to the caller. Implementation Requirements:
The default implementation behaves as if:
for (T t : this)
action.accept(t);
Parameters: action - The action to be performed for each element
Throws: NullPointerException - if the specified action is null
Since: 1.8
1. set.stream().forEach(System.out::println); // It simply uses stream to display set values
2. set.forEach(System.out::println); // It uses Enhanced forEach to display set values
同样,如果这个集合是自定义类类型,例如:Customer。
Set<Customer> setCust = new HashSet<>();
Customer c1 = new Customer(1, "Hena", 20);
Customer c2 = new Customer(2, "Meena", 24);
Customer c3 = new Customer(3, "Rahul", 30);
setCust.add(c1);
setCust.add(c2);
setCust.add(c3);
setCust.forEach((k) -> System.out.println(k.getId()+" "+k.getName()+" "+k.getAge()));
//客户类:
class Customer{
private int id;
private String name;
private int age;
public Customer(int id,String name,int age){
this.id=id;
this.name=name;
this.age=age;
} // Getter, Setter methods are present.}