public class transferColleElements { //数组引用 @Test public void test(){ List<Person2> rosterAsArray = Arrays.asList(new Person2(100, "zangliang"), new Person2(1, "anan"), new Person2(120, "ananma")); Set<Person2> rosterSetLambda = Person2.transferElements(rosterAsArray,() -> { return new HashSet<Person2>(); } ); // // Set<Person2> rosterSet1 = Person2.transferElements(rosterAsArray, HashSet<Person2>::new); // // Set<Person2> rosterSet2 = Person2.transferElements(rosterAsArray, HashSet::new); for (Person2 person : rosterSetLambda) { System.out.println(person.name); } } } class Person2 { public enum Sex { MALE, FEMALE } public Person2(Integer age,String name) { this.age=age; this.name=name; } String name; Calendar birthday; Integer age; public int getAge() { return age; } public Calendar getBirthday() { return birthday; } public static int compareByAge(Person a, Person b) { return a.age.compareTo(b.age); } //功能接口Supplier包含一个get不带任何参数并返回一个对象的方法。因此,您可以transferElements使用lambda表达式调用该方法 public static <T, SOURCE extends Collection<T>, DEST extends Collection<T>> DEST transferElements(SOURCE sourceCollection, Supplier<DEST> collectionFactory) { DEST result = collectionFactory.get(); for (T t : sourceCollection) { result.add(t); } return result; } }
lamda表达式构造函数,一个集合的元素转移到另一个元集合
最新推荐文章于 2023-06-06 16:45:54 发布