Lambda Expressions (Method Reference)

Lambda Expressions

1.Reference to a static method

    @Test(dataProvider = "persons")
    public void testSortPersons2(Person[] persons) {
        Arrays.sort(persons, PersonUtil::compareByAge);
        assertSortedPersons(persons);
    }

2.Reference to an instance method of a particular object

    @Test(dataProvider = "persons")
    public void testSortPersons3(Person[] persons) {
        Arrays.sort(persons, sean::compareByAge);
        assertSortedPersons(persons);
    }

3.Reference to an instance method of an arbitrary object of a particular type

    public void testSortNames() {
        String[] names = { sean.getName(), wanyu.getName(), shaohan.getName(), mohan.getName() };
        Arrays.sort(names, String::compareToIgnoreCase);
        assertEquals(mohan.getName(), names[0]);
        assertEquals(sean.getName(), names[1]);
        assertEquals(shaohan.getName(), names[2]);
        assertEquals(wanyu.getName(), names[3]);
    }

4.Reference to a constructor

    @Test(dataProvider = "persons")
    public void testTransferElements(Person[] persons) {
        Set newPersons = PersonUtil.transferElements(Arrays.asList(persons), HashSet::new);
        assertTrue(newPersons.size() == 4);
        assertTrue(newPersons.contains(shaohan));
        assertTrue(newPersons.contains(mohan));
        assertTrue(newPersons.contains(sean));
        assertTrue(newPersons.contains(wanyu));
    }

你可能感兴趣的:(java,lambda)