Java Reference
In-Depth Information
catch (IOException e) {
e.printStackTrace();
}
}
public static void listFileTree() {
Path dir = Paths.get("");
System.out.printf("%nThe file tree for %s%n", dir.toAbsolutePath());
try(Stream<Path> fileTree = Files.walk(dir)) {
fileTree.forEach(System.out::println);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
STRANGE fits of passion have I known:
And I will dare to tell,
But in the lover's ear alone,
What once to me befell.
The file tree for C:\book\javabook
build
build\built-jar.properties
...
Streams from Other Sources
Java 8 has added methods in many other classes to return the contents they represent in a stream. Two such methods
that you may use frequently are explained next.
The
chars()
method in the
CharSequence
interface returns an
IntStream
whose elements are
int
values
representing the characters of the
CharSequence
. You can use the
chars()
method on a
String
, a
StringBuilder
,
and a
StringBuffer
to obtain a stream of characters of their contents as these classes implement the
CharSequence
interface.
splitAsStream(CharSequence input)
method of the
java.util.regex.Pattern
class
returns a stream of
String
whose elements match the pattern.
Let's look at an example in both categories. The following snippet of code creates a stream of characters from
a string, filters out all digits and whitespaces, and prints the remaining characters:
•
The
String str = "5 apples and 25 oranges";
str.chars()
.filter(n -> !Character.isDigit((char)n) && !Character.isWhitespace((char)n))
.forEach(n -> System.out.print((char)n));
applesandoranges