首页 / JAVA / java8之lambda表达式入门
java8之lambda表达式入门
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java8之lambda表达式入门,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含12284字,纯文字阅读大概需要18分钟。
内容图文
class Student{ private String name; private Double score; public Student(String name, Double score) { this.name = name; this.score = score; } public String getName() { return name; } public Double getScore() { return score; } public void setName(String name) { this.name = name; } public void setScore(Double score) { this.score = score; } @Override public String toString() { return "{" + "\"name\":\"" + name + "\"" + ", \"score\":\"" + score + "\"" + "}"; } }: @Test public void test1(){ List<Student> studentList = new ArrayList<Student>(){ { add(new Student("stu1",100.0)); add(new Student("stu2",97.0)); add(new Student("stu3",96.0)); add(new Student("stu4",95.0)); } }; Collections.sort(studentList, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return Double.compare(o1.getScore(),o2.getScore()); } }); System.out.println(studentList); }
代码调用Collections.sort方法对集合进行排序,其中第二个参数是一个匿名内部类,sort方法调用内部类中的compare方法对list进行位置交换,因为java中的参数类型只能是类或者基本数据类型,所以虽然传入的是一个Comparator类,但是实际上可以理解成为了传递compare方法而不得不传递一个Comparator类 ,这种方式显得比较笨拙,而且大量使用的话代码严重冗余,这种情况在java8中通过使用lambda表达式来解决。
@FunctionalInterface public interface Comparator<T> { int compare(T o1, T o2); }
public void test1_(){ List<Student> studentList = new ArrayList<Student>(){ { add(new Student("stu1",100.0)); add(new Student("stu2",97.0)); add(new Student("stu3",96.0)); add(new Student("stu4",95.0)); } }; Collections.sort(studentList,(s1,s2)-> Double.compare(s1.getScore(),s2.getScore())); System.out.println(studentList); }
public void testThread(){ new Thread(new Runnable() { @Override publicvoid run() { System.out.println("hello, i am thread!"); } }).start(); }
@FunctionalInterface public interface Runnable { /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object‘s * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run(); }
public void testThread_(){ new Thread(()-> System.out.println("hello, i am thread!")).start(); }
@FunctionalInterface public interface MyFunctionalInterface { public void single(String msg); } /** * 需要单个参数 */ public static void testOnePar(MyFunctionalInterface myFunctionalInterface){ myFunctionalInterface.single("msg"); } /** * 一个参数,可以省略参数的括号 */ @Test publicvoid testOneParameter(){ testOnePar(x-> System.out.println(x)); }
/** * 需要单个参数 */ public static void testOnePar1(Consumer unaryOperator){ unaryOperator.accept("msg"); }
public static void test1_() { List<String> strLst = new ArrayList<String>() { { add("adfkjsdkfjdskjfkds"); add("asdfasdfafgfgf"); add("public static void main"); } }; Collections.sort(strLst, String::compareToIgnoreCase); System.out.println(strLst); }
class Father { public void greet() { System.out.println("Hello, i am function in father!"); } } class Child extends Father { @Override publicvoid greet() { Runnable runnable = super::greet; new Thread(runnable).start(); } } publicstaticvoid main(String[] args){ new Child().greet(); }
List<String> labels = Arrays.asList("aaa","bbb","ccc","ddd"); Stream<Button> buttonStream = labels.stream().map(Button::new);
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
public class Button extends ButtonBase { /** * Creates a button with the specified text as its label. * * @param text A text string for its label. */public Button(String text) { super(text); initialize(); } }
Button[] buttons1 = buttonStream.toArray(Button[]::new);
<A> A[] toArray(IntFunction<A[]> generator);
public class LambdaTest3 { @Test public void test1_(){ List<Integer> list = this.asList(ArrayList::new ,1,2,3,4,5); list.forEach(System.out::println); } public <T> List<T> asList(MyCrator<List<T>> creator,T... a){ List<T> list = creator.create(); for (T t : a) list.add(t); return list; } } interface MyCrator<T extends List<?>>{ T create(); }
public static <T> List<T> asList(T... a) { returnnew ArrayList<>(a); }
public class LambdaTest4 { public void doWork1(){ Runnable runnable = ()->{ System.out.println(this.toString()); System.out.println("lambda express run..."); }; new Thread(runnable).start(); } publicvoid doWork2(){ Runnable runnable = new Runnable() { @Override publicvoid run() { System.out.println(this.toString()); System.out.println("anony function run..."); } }; new Thread(runnable).start(); } publicstaticvoid main(String[] args) { new LambdaTest4().doWork1(); new LambdaTest4().doWork2(); } }
com.java8.lambda.LambdaTest4@74f84cf lambda express run... com.java8.lambda.LambdaTest4$1@4295c176 anony function run...
public class Outer { public AnnoInner getAnnoInner(int x) { int y = 100; returnnew AnnoInner() { int z = 100; @Override publicint add() { return x + y + z; } }; } public AnnoInner AnnoInnergetAnnoInner1(List<Integer> list1) { List<Integer> list2 = new ArrayList<>(Arrays.asList(1, 2, 3)); return ()->{ list2.add(123); int count = 0; Iterator<Integer> it = list1.iterator(); while (it.hasNext()){ count+=it.next(); } Iterator<Integer> it1 = list2.iterator(); while (it1.hasNext()){ count+=it1.next(); } return count; }; } @Test publicvoid test(){ AnnoInner res = new Outer().AnnoInnergetAnnoInner1(new ArrayList<>(Arrays.asList(1,2,3))); System.out.println(res.add()); } } interface AnnoInner { int add(); }
@FunctionalInterface public interface Comparator<T> { int compare(T o1, T o2); boolean equals(Object obj); default Comparator<T> reversed() { return Collections.reverseOrder(this); } default Comparator<T> thenComparing(Comparator<? super T> other) { Objects.requireNonNull(other); return (Comparator<T> & Serializable) (c1, c2) -> { int res = compare(c1, c2); return (res != 0) ? res : other.compare(c1, c2); }; } default <U> Comparator<T> thenComparing( Function<? super T, ? extends U> keyExtractor, Comparator<? super U> keyComparator) { return thenComparing(comparing(keyExtractor, keyComparator)); } default <U extends Comparable<? super U>> Comparator<T> thenComparing( Function<? super T, ? extends U> keyExtractor) { return thenComparing(comparing(keyExtractor)); } default Comparator<T> thenComparingInt(ToIntFunction<? super T> keyExtractor) { return thenComparing(comparingInt(keyExtractor)); } default Comparator<T> thenComparingLong(ToLongFunction<? super T> keyExtractor) { return thenComparing(comparingLong(keyExtractor)); } default Comparator<T> thenComparingDouble(ToDoubleFunction<? super T> keyExtractor) { return thenComparing(comparingDouble(keyExtractor)); } publicstatic <T extends Comparable<? super T>> Comparator<T> reverseOrder() { return Collections.reverseOrder(); } @SuppressWarnings("unchecked") publicstatic <T extends Comparable<? super T>> Comparator<T> naturalOrder() { return (Comparator<T>) Comparators.NaturalOrderComparator.INSTANCE; } publicstatic <T> Comparator<T> nullsFirst(Comparator<? super T> comparator) { returnnew Comparators.NullComparator<>(true, comparator); } publicstatic <T> Comparator<T> nullsLast(Comparator<? super T> comparator) { returnnew Comparators.NullComparator<>(false, comparator); } publicstatic <T, U> Comparator<T> comparing( Function<? super T, ? extends U> keyExtractor, Comparator<? super U> keyComparator) { Objects.requireNonNull(keyExtractor); Objects.requireNonNull(keyComparator); return (Comparator<T> & Serializable) (c1, c2) -> keyComparator.compare(keyExtractor.apply(c1), keyExtractor.apply(c2)); } publicstatic <T, U extends Comparable<? super U>> Comparator<T> comparing( Function<? super T, ? extends U> keyExtractor) { Objects.requireNonNull(keyExtractor); return (Comparator<T> & Serializable) (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2)); } publicstatic <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) { Objects.requireNonNull(keyExtractor); return (Comparator<T> & Serializable) (c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2)); } publicstatic <T> Comparator<T> comparingLong(ToLongFunction<? super T> keyExtractor) { Objects.requireNonNull(keyExtractor); return (Comparator<T> & Serializable) (c1, c2) -> Long.compare(keyExtractor.applyAsLong(c1), keyExtractor.applyAsLong(c2)); } publicstatic<T> Comparator<T> comparingDouble(ToDoubleFunction<? super T> keyExtractor) { Objects.requireNonNull(keyExtractor); return (Comparator<T> & Serializable) (c1, c2) -> Double.compare(keyExtractor.applyAsDouble(c1), keyExtractor.applyAsDouble(c2)); } }
public class LambdaTest5 implements myInterface1, myInterface2 { @Override publicvoid getName() { myInterface1.super.getName(); } publicstaticvoid main(String[] args) { new LambdaTest5().getName(); } } interface myInterface1 { defaultvoid getName() { System.out.println("myInterface1 getName"); } ; } interface myInterface2 { defaultvoid getName() { System.out.println("myInterface2 getName"); } }
原文:http://www.cnblogs.com/andywithu/p/7357069.html
内容总结
以上是互联网集市为您收集整理的java8之lambda表达式入门全部内容,希望文章能够帮你解决java8之lambda表达式入门所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。