JDK1.8新特性——使用新的方式遍历集合

时间:2023-03-09 16:09:40
JDK1.8新特性——使用新的方式遍历集合

JDK1.8新特性——使用新的方式遍历集合

摘要:本文主要学习了在JDK1.8中新增的遍历集合的方式。

遍历List

方法:

 default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}

实例:

 public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("张三");
list.add("李四");
list.add("王五");
list.add("赵六");
list.forEach(e -> System.out.println(e));
}

遍历Set

方法:

 default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}

实例:

 public static void main(String[] args) {
Set<String> set = new HashSet<String>();
set.add("张三");
set.add("李四");
set.add("王五");
set.add("赵六");
set.forEach(e -> System.out.println(e));
}

遍历Map

方法:

 default void forEach(BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
for (Map.Entry<K, V> entry : entrySet()) {
K k;
V v;
try {
k = entry.getKey();
v = entry.getValue();
} catch(IllegalStateException ise) {
// this usually means the entry is no longer in the map.
throw new ConcurrentModificationException(ise);
}
action.accept(k, v);
}
}

实例:

 public static void main(String[] args) {
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(101, "张三");
map.put(102, "李四");
map.put(103, "王五");
map.put(104, "赵六");
map.forEach((key, value) -> System.out.println(key+"->"+value));
}

相关文章