楼主: ReneeBK
2570 27

[Ken Kousen]Modern Java Recipes [推广有奖]

21
ReneeBK(未真实交易用户) 发表于 2017-8-7 04:07:40
  1. Example 4-15. Output of summary statistics calculation
  2. DoubleSummaryStatistics{count=10000, sum=4983.859228, min=0.000264,
  3. average=0.498386, max=0.999998}
  4. Other reduction operations like sum, count, max, min, and average do what
  5. you would expect. The only interesting part is that some of them return
  6. optionals, because if there are no elements in the stream (perhaps after a
  7. filtering operation) the result is undefined or null.
复制代码

22
ReneeBK(未真实交易用户) 发表于 2017-8-7 04:26:35
  1. Example 4-17. Printing the values of x and y
  2. int sum = IntStream.rangeClosed(1, 10)
  3. .reduce((x, y) -> {
  4. System.out.printf("x=%d, y=%d%n", x, y);
  5. return x + y;
  6. }).orElse(0);
复制代码

23
ReneeBK(未真实交易用户) 发表于 2017-8-7 04:28:36
  1. Example 4-20. Doubling the values during the sum (WORKS)
  2. int doubleSum = IntStream.rangeClosed(1, 10)
  3. .reduce(0, (x, y) -> x + 2 * y);
  4. // doubleSum == 110 (yay!)
  5. By providing the initial value of zero for the accumulator x, the value of y is
  6. assigned to each of the elements in the stream, doubling them all.
复制代码

24
Lisrelchen(未真实交易用户) 发表于 2017-8-21 10:53:42
  1. Example 5-1. Returning a collection and filtering out nulls
  2. List<String> strings = Arrays.asList(
  3. "this", null, "is", "a", null, "list", "of", "strings", null);
  4. List<String> nonNullStrings = strings.stream()
  5. .filter(Objects::nonNull)
  6. .collect(Collectors.toList());
复制代码

25
Lisrelchen(未真实交易用户) 发表于 2017-8-21 10:54:12
  1. Example 5-2. Testing the filter
  2. @Test
  3. public void testNonNulls() throws Exception {
  4. List<String> strings =
  5. Arrays.asList("this", "is", "a", "list", "of", "strings");
  6. assertTrue(Objects.deepEquals(strings, nonNullStrings);
  7. }
复制代码

26
Lisrelchen(未真实交易用户) 发表于 2017-8-21 10:54:47
  1. Example 5-3. Filtering nulls from a generic list
  2. public <T> List<T> getNonNullElements(List<T> list) {
  3. return list.stream()
  4. .filter(Objects::nonNull)
  5. .collect(Collectors.toList());
  6. }
复制代码

27
Lisrelchen(未真实交易用户) 发表于 2017-8-21 10:56:40
  1. Example 5-5. Lambda expression for the listener
  2. String greeting = "Hello, %s!";
  3. button.addActionListener(e ->
  4. response.setText(String.format(greeting,name.getText())));
复制代码

28
Lisrelchen(未真实交易用户) 发表于 2017-8-21 10:57:51
  1. Example 5-6. Sum the values in a List
  2. List<Integer> nums = Arrays.asList(3, 1, 4, 1, 5, 9);
  3. int total = 0;
  4. for (int n : nums) {
  5. total += n;
  6. }
  7. total = 0;
  8. nums.forEach(n -> total += n);
  9. total = nums.stream()
  10. .mapToInt(Integer::valueOf)
  11. .sum()
复制代码

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注jltj
拉您入交流群
GMT+8, 2026-3-4 08:52