双冒号(::)主要使用形式包括:
类名::实例方法
对象::实例方法
下面通过代码示例,详细解说。
双冒号(::)和 箭头函数(->)一并展示如下:
如:HashMap::new 等同于 ( ) -> new HashMap()
1 public class Test {
2
3 // 实例对象引用实例方法
4 Supplier supplier1 = "lowerCase"::toUpperCase;
5 Supplier supplier1_1 = () -> "lowerCase".toUpperCase();
6
7 // 类引用(无参)构造函数
8 Supplier supplier2 = String::new;
9 Supplier supplier2_1 = () -> new String();
10
11 // 类引用(有参)构造函数
12 Function function1 = String::new;
13 Function function1_1 = (String str) -> new String(str);
14
15 // 类引用实例方法,入参为传入实例对象,入参、出参同类型
16 Function function2 = String::toUpperCase;
17 Function function2_1 = (String str) -> str.toUpperCase();
18
19 // Predicate可理解为特殊的Function
20
21 Person person = new Person();
22 // 须为无参静态方法
23 Supplier supplierBln = Person::isTest;
24 Supplier supplierBln_1 = () -> Person.isTest();
25
26 // 实例对象调用实例方法
27 Supplier supplierStr = person::getName;
28 Supplier supplierStr_1 = () -> person.getName();
29
30 // 无参构造函数
31 Supplier supplierPerson = Person::new;
32 Supplier supplierPerson_1 = () -> new Person();
33
34 // 有参构造函数
35 BiFunction biFunction = Person::new;
36 BiFunction biFunction_1 = (name, gender) -> new Person(name, gender);
37
38 // 类名调用实例方法,入参为传入实例对象
39 Function functionP = Person::toOpposite;
40 Function functionP_1 = person -> person.toOpposite();
41
42 Consumer consumer = System.out::println;
43 Consumer consumer_1 = (String str) -> System.out.println(str);;
44
45 public static void main(String[] args) {
46 List list = Arrays.asList("1", "2", "3");
47 boolean bl = list.stream().anyMatch("1"::equals);
48 List retval = list.stream().collect(Collectors.toCollection(LinkedList::new));
49
50 List persons = Arrays.asList(new Person(10, "Jack", "M"));
51 Person person = new Person(20, "Lily", "F");
52 persons.stream().filter(Person::isMale).filter(person::isUnder).collect(Collectors.toCollection(ArrayList::new));
53 }
54 }
Person类代码如下:
1 public class Person {
2 int age;
3 String name;
4 String gender;
5
6 public Person() {
7 }
8
9 public Person(String name) {
10 this.name = name;
11 }
12
13 public Person(String name, String gender) {
14 this.name = name;
15 this.gender = gender;
16 }
17
18 public Person(int age, String name, String gender) {
19 this.age = age;
20 this.name = name;
21 this.gender = gender;
22 }
23
24 public String getName() {
25 return this.name;
26 }
27
28 public Person toOpposite() {
29 if (gender.charAt(0) == 'M')
30 gender = "F";
31 else
32 gender = "M";
33 return this;
34 }
35
36 public static boolean isTest() {
37 return true;
38 }
39
40 public boolean isUnder(Person person) {
41 return person.age > this.age;
42 }
43
44 public boolean isMale() {
45 return gender.equals("M");
46 }
47 }
标签:java,String,示例,gender,name,Person,new,public,lambda
来源: https://www.cnblogs.com/blouson/p/Java_colon_operator.html