为什么导入 java.util.* 不足以导入流?

Why importing java.util.* is not enough to import stream?

简短版本:

我知道导入 * 是一种不好的做法,最好导入我们明确需要的内容。但是,我很好奇为什么导入 util.* 不包括 util.stream.*.

长版:

如果我import java.util.stream.*;

这段代码运行成功:

int[] a = {3, 4, 1};
ArrayList<Integer> list = Arrays.stream(a)
                          .boxed()
                          .collect(Collectors.toCollection(ArrayList::new));

但是,如果我从 import 中删除 stream

import java.util.*;

失败:

Main.java:20: error: cannot find symbol
                                .collect(Collectors.toCollection(ArrayList::new));
                                         ^
  symbol:   variable Collectors
  location: class Ideone
1 error

我试过 Java 8 (1.8.0_201):

https://www.onlinegdb.com/online_java_compiler

Java11 (11.0.11+9-Ubuntu-0ubuntu2.20.04):

https://www.programiz.com/java-programming/online-compiler/

和Java 12 (12.0.1+12):

https://ideone.com/7XfIFY

您正在使用 wildcard import 导入包 not the sub-packages inside it.

中的所有 类
import java.util.*;

上面的导入语句将导入 java.util 包内的所有 Classes 而不是子包,即 java.util.stream ,所以为了导入它,你需要有像

这样的导入语句
import java.util.*;
import java.util.stream.*;

Read more on Importing packages

虽然包名看起来更像是一种层次关系的体现,其实不然。

包名最像是 class 的前缀。

具体说明请参考official document(包的表层结构)