From af0baf706e2fca04b50346c5c53fc4099b7e86ff Mon Sep 17 00:00:00 2001 From: wizardforcel <562826179@qq.com> Date: Fri, 22 Jul 2016 16:05:25 +0800 Subject: [PATCH] ch7 --- ch4.md | 2 +- ch7.md | 250 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ch8.md | 2 +- 3 files changed, 252 insertions(+), 2 deletions(-) create mode 100644 ch7.md diff --git a/ch4.md b/ch4.md index 01b157b..d2d2736 100644 --- a/ch4.md +++ b/ch4.md @@ -323,7 +323,7 @@ executor.scheduleWithFixedDelay(task, 0, 1, TimeUnit.SECONDS); 这个例子调度了一个任务,并在一次执行的结束和下一次执行的开始之间设置了一个1分钟的固定延迟。初始化延迟为0,任务执行时间为0。所以我们分别在0s,3s,6s,9s等间隔处结束一次执行。如你所见,`scheduleWithFixedDelay()`在你不能预测调度任务的执行时长时是很有用的。 -这是并发系列教程的第一部分。我推荐你亲手实践一下上面的代码示例。你可以从 [Github](https://github.com/winterbe/java8-tutorial) 上找到这篇文章中所有的代码示例,所以欢迎你fork这个repo,[给我星星](https://github.com/winterbe/java8-tutorial/stargazers)。 +这是并发系列教程的第一部分。我推荐你亲手实践一下上面的代码示例。你可以从 [Github](https://github.com/winterbe/java8-tutorial) 上找到这篇文章中所有的代码示例,所以欢迎你fork这个仓库,并[收藏它](https://github.com/winterbe/java8-tutorial/stargazers)。 我希望你会喜欢这篇文章。如果你有任何的问题都可以在下面评论或者通过 [Twitter](https://twitter.com/winterbe_) 给我回复。 diff --git a/ch7.md b/ch7.md new file mode 100644 index 0000000..3d2878e --- /dev/null +++ b/ch7.md @@ -0,0 +1,250 @@ +# Java 8 API ʾֵַļ + +> ԭģ[Java 8 API by Example: Strings, Numbers, Math and Files](http://winterbe.com/posts/2015/03/25/java8-examples-string-number-math-files/) + +> ߣ[](https://github.com/wizardforcel) + +> Э飺[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) + +Ľ̳̺¶漰Java8Ҫĸı䣬[lambdaʽ](ch1.md)[ʽ](ch2.md)Ǵִ[JDK 8 API](http://winterbe.com/posts/2014/03/29/jdk8-api-explorer/)ҲĽһЩʵõԺͷ + +ƪ̳漰Java 8 APIеЩС޸ -- ÿʹü׶ĴʾǺúÿһֵַļ + +## ַ + +µķַʹã`join``chars`һʹָķָκַΪһַ + +```java +String.join(":", "foobar", "foo", "bar"); +// => foobar:foo:bar +``` + +ڶ`chars`ַַЩַʹʽ + +```java +"foobar:foo:bar" + .chars() + .distinct() + .mapToObj(c -> String.valueOf((char)c)) + .sorted() + .collect(Collectors.joining()); +// => :abfor +``` + +ַʽģʽҲǿԷָκģʽǣǽַָΪַ + +```java +Pattern.compile(":") + .splitAsStream("foobar:foo:bar") + .filter(s -> s.contains("bar")) + .sorted() + .collect(Collectors.joining(":")); +// => bar:foobar +``` + +⣬ģʽתΪνʡЩνʿڹַ + +```java +Pattern pattern = Pattern.compile(".*@gmail\\.com"); +Stream.of("bob@gmail.com", "alice@hotmail.com") + .filter(pattern.asPredicate()) + .count(); +// => 1 +``` + +ģʽκ`@gmail.com`βַ֮Java8`Predicate`˵ʼַ + +## ֵ + +Java8˶޷Ķ֧֡Javaеֵзŵģ磬۲`Integer` + +`int`ɱʾΪ`2 ** 32`֡JavaеֵĬΪзŵģһֱʾţ0Ϊ1ΪԴʮƵ0ʼзΪ`2 ** 31 - 1` + +ͨ`Integer.MAX_VALUE` + +```java +System.out.println(Integer.MAX_VALUE); // 2147483647 +System.out.println(Integer.MAX_VALUE + 1); // -2147483648 +``` + +Java8˽޷֧֣ǿι + +```java +long maxUnsignedInt = (1l << 32) - 1; +String string = String.valueOf(maxUnsignedInt); +int unsignedInt = Integer.parseUnsignedInt(string, 10); +String string2 = Integer.toUnsignedString(unsignedInt, 10); +``` + +㿴ڿԽ޷`2 ** 32 - 1`ΪҲԽֵת޷ַʾ + +֮ǰʹ`parseInt`ɣչʾ + +```java +try { + Integer.parseInt(string, 10); +} +catch (NumberFormatException e) { + System.err.println("could not parse signed int of " + maxUnsignedInt); +} +``` + +ֵɽΪзΪΧ`2 ** 31 - 1` + +## + +`Math`һЩֵʲô˼أѾֵͶֵԵĽܱĴСװʱᷢʲôأ + +```java +System.out.println(Integer.MAX_VALUE); // 2147483647 +System.out.println(Integer.MAX_VALUE + 1); // -2147483648 +``` + +㿴ͨDzԸ⿴ġ + +Java8ϸѧ֧⡣`Math`չһЩȫ`exact`β`addExact`ֵܱװʱЩͨ׳`ArithmeticException`쳣ش + +```java +try { + Math.addExact(Integer.MAX_VALUE, 1); +} +catch (ArithmeticException e) { + System.err.println(e.getMessage()); + // => integer overflow +} +``` + +ͨ`toIntExact`תΪʱܻ׳ͬ쳣 + +```java +try { + Math.toIntExact(Long.MAX_VALUE); +} +catch (ArithmeticException e) { + System.err.println(e.getMessage()); + // => integer overflow +} +``` + +## ļ + +`Files`״Java7룬ΪNIOһ֡JDK8 APIһЩķǿԽļںʽ̽һЩʾ + +### гļ + +`Files.list`ָĿ¼·תΪļϵͳʹ`filter``sorted` + +```java +try (Stream stream = Files.list(Paths.get(""))) { + String joined = stream + .map(String::valueOf) + .filter(path -> !path.startsWith(".")) + .sorted() + .collect(Collectors.joining("; ")); + System.out.println("List: " + joined); +} +``` + +г˵ǰĿ¼ļ֮ÿ·ӳΪַʾ֮ˡΪһַ㻹ϤʽӦĶҵ[Java8̳](ch2.md) + +Ѿע⵽Ĵװ`try-with`Сʵ`AutoCloseable`ҪʽرΪIO + +> ص`DirectoryStream`ķװҪʱļԴӦʹ`try-with`ṹȷʽɺ`close`á + +### ļ + +ʾβĿ¼Ŀ¼µļ + +```java +Path start = Paths.get(""); +int maxDepth = 5; +try (Stream stream = Files.find(start, maxDepth, (path, attr) -> + String.valueOf(path).endsWith(".js"))) { + String joined = stream + .sorted() + .map(String::valueOf) + .collect(Collectors.joining("; ")); + System.out.println("Found: " + joined); +} +``` + +`find`Ŀ¼·`start`ʼ㣬`maxDepth`ȡһƥνʣ߼УJavaScirptļ`.js`βļ + +ǿʹ`Files.walk`ͬΪÿļҪνʡ + +```java +Path start = Paths.get(""); +int maxDepth = 5; +try (Stream stream = Files.walk(start, maxDepth)) { + String joined = stream + .map(String::valueOf) + .filter(path -> path.endsWith(".js")) + .sorted() + .collect(Collectors.joining("; ")); + System.out.println("walk(): " + joined); +} +``` + +Уʹʽ`filter`ɺϸͬΪ + +### дļ + +ıļڴ棬ԼıļдַJava 8 Ǽ򵥵񡣲ҪȥŪдˡ`Files.readAllLines`ָļжַбСԼ򵥵޸бҽͨ`Files.write`дһļУ + +```java +List lines = Files.readAllLines(Paths.get("res/nashorn1.js")); +lines.add("print('foobar');"); +Files.write(Paths.get("res/nashorn1-modified.js"), lines); +``` + +ҪעЩڴ沢ʮָЧΪļڴ档ļԽõĶҲԽ + +ʹ`Files.lines`ΪڴЧȡÿһУʹúʽʽһ԰жڴ档 + +```java +try (Stream stream = Files.lines(Paths.get("res/nashorn1.js"))) { + stream + .filter(line -> line.contains("print")) + .map(String::trim) + .forEach(System.out::println); +} +``` + +ҪľϸƣҪһµ`BufferedReader`棺 + +```java +Path path = Paths.get("res/nashorn1.js"); +try (BufferedReader reader = Files.newBufferedReader(path)) { + System.out.println(reader.readLine()); +} +``` + +ߣҪдļʱ򵥵عһ`BufferedWriter`棺 + +```java +Path path = Paths.get("res/output.js"); +try (BufferedWriter writer = Files.newBufferedWriter(path)) { + writer.write("print('Hello World');"); +} +``` + +`BufferedReader`ҲԷʺʽ`lines`湹 + +```java +Path path = Paths.get("res/nashorn1.js"); +try (BufferedReader reader = Files.newBufferedReader(path)) { + long countPrints = reader + .lines() + .filter(line -> line.contains("print")) + .count(); + System.out.println(countPrints); +} +``` + +ĿǰΪֹԿJava8ṩ򵥵ķȡıļÿһУʹļӱݡ + +ҵҪʽʹ`try-with`رļʹʾЩҡڴʽڵ`count``collect`ʱԶرգΪ㲻ͬϵֹΡ + +ϣϲƪ¡ʾ붼й[Github](https://github.com/winterbe/java8-tutorial)ϣԴҲ[Java8](http://winterbe.com/java/)ĴĴƬΡƪ¶[ղ](https://github.com/winterbe/java8-tutorial)ҵIJֿ⣬Twitter[ע](https://twitter.com/winterbe_) + +ֱ̣ diff --git a/ch8.md b/ch8.md index 5fcb8f0..2f0e70f 100644 --- a/ch8.md +++ b/ch8.md @@ -88,4 +88,4 @@ public static Optional resolve(Supplier resolver) { 像往常一样,上面的示例代码都[托管在 GitHub](https://github.com/winterbe/java8-tutorial)。 -祝编码愉快! +祝编程愉快! -- GitLab