[JAVA] 类::对象方法 的用法

“::”,除了 对象::对象方法 和 类::静态方法 外:

// 例子
System.out::println
Math::abs

从《Java 核心技术》中,可以看到还有另一种用法:类::对象方法

// 例子
String::compare
// 以上例子等价于:
(x, y)->x.compare(y)
//  如果存在这样一个接口:
interface Test{
   int comp(String x,String y);
}
// 那么有:
Test t = String::compareTo;
System.out.println(t.comp("Apple", "Bob"));// -1

具体的例子:

poem.txt

From fairest creatures we desire increase,
That thereby beauty's rose might never die,
But as the riper should by time decease,
His tender heir might bear his memory;
But thou, contracted to thine own bright eyes,
Feed'st thy light's flame with self-substantial fuel,
Making a famine where abundance lies,
Thyself thy foe, to thy sweet self too cruel.
Thout that are now the world's fresh ornament
And only herald to the gaudy spring,
Within thine own bud buriest thy content
And, tender churl, mak'st waste in niggarding.
Pity the world, or else this glutton be,
To eat the world's due, by the grave and thee.

Demo.java中的main方法:

List<String> text = Files.readAllLines(Paths.get("poem.txt"), StandardCharsets.UTF_8);

Map<String, Integer> count = new TreeMap<>();

text.stream()
  .flatMap(line -> Arrays.stream(line.replaceAll("[,.;]","")
  .split("\\s+")))
  .map(String::toLowerCase)
  .forEach(word -> count.put(word, count.getOrDefault(word, 0) + 1));

count.keySet().stream()
  .sorted(Comparator.comparing(String::length)
  .thenComparing(String::compareTo))// KO↑KO↓
  .forEach(key -> System.out.printf("%s: %d%n", key, count.get(key)));

输出:

a: 1
as: 1
be: 1
.
.
.
contracted: 1
niggarding: 1
self-substantial: 1

发表评论