// 함수 객체로 정렬하기 (254-255쪽) publicclassSortFourWays { publicstaticvoidmain(String[] args) { List<String> words = Arrays.asList("a","b","c");
// 코드 42-1 익명 클래스의 인스턴스를 함수 객체로 사용 - 낡은 기법이다! (254쪽) Collections.sort(words, newComparator<String>() { publicintcompare(String s1, String s2) { return Integer.compare(s1.length(), s2.length()); } }); System.out.println(words); Collections.shuffle(words);
// 코드 42-2 람다식을 함수 객체로 사용 - 익명 클래스 대체 (255쪽) Collections.sort(words, (s1, s2) -> Integer.compare(s1.length(), s2.length())); System.out.println(words); Collections.shuffle(words);
// 람다 자리에 비교자 생성 메서드(메서드 참조와 함께)를 사용 (255쪽) Collections.sort(words, comparingInt(String::length)); System.out.println(words); Collections.shuffle(words);
// 비교자 생성 메서드와 List.sort를 사용 (255쪽) words.sort(comparingInt(String::length)); System.out.println(words); } }
/* * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.function;
/** * Represents an operation upon two {@code double}-valued operands and producing a * {@code double}-valued result. This is the primitive type specialization of * {@link BinaryOperator} for {@code double}. * * <p>This is a <a href="package-summary.html">functional interface</a> * whose functional method is {@link #applyAsDouble(double, double)}. * * @see BinaryOperator * @see DoubleUnaryOperator * @since 1.8 */ @FunctionalInterface publicinterfaceDoubleBinaryOperator { /** * Applies this operator to the given operands. * * @param left the first operand * @param right the second operand * @return the operator result */ doubleapplyAsDouble(double left, double right); }
위처럼 간결하게 변할수 있는데 이것은 jdk 1.8에 추가된 DoubleBinaryOperator를 활용해서 바꾼것이다.
람다는 이름도 없고 문서화도 못한다. 따라서 코드자체로 동작이 명확하게 설명되지 않거나 코드 라인수가 많아지면 람다를 쓰지 말아야 된다.