Lambda Expression

Lambda Expressions are nameless functions given as constant values. They can appear anywhere that any other constant may, but are typically written as a parameter to some other function. The canonical example is that you'll pass a comparison function to a generic "sort" routine, and instead of going to the trouble of defining a whole function (and incurring the lexical discontinuity and namespace pollution) to describe this comparison, you can just pass a lambda expression describing the comparison.

HOWEVER, this misses one of the most important features of Lambda Expressions, which is that they execute in the context of their appearance. Therefore, they can use the values of the variables that are defined in that context. This differentiates function-pointers from true lambda expressions. In languages supporting mutable variables, proper lambda expressions offer the power to change the values of those variables.

Lambda expressions appear (with different syntax) in all LISPs, Perl, Python, and sufficiently-recent versions of C++, Objective C, C# and Java 8, but notably not in C even though it has a way to deal with passing functions (or some excuse for them) around as parameters. They are a syntax element with particular semantics, and those semantics place more requirements on the runtime than C was designed to require.

Java 8 Lambda and Sorting

Java 中 lambda 表达式的形式:

(arguments) -> (body)

一个 lambda 表达式可以有 01 或多个参数:
() -> System.out.println("Hello World") 
 a -> System.out.println(a) 
(a, b) -> System.out.println(a + " " + b)

参数可以在表达式中声明也可以从上下文中被推导:
(int a) is the same as (a)

lambda 表达式中可以有 0,1 或多句代码,如果有零个或多个语句存在,必须使用大括号:
() -> {} //this does nothing it takes no arguments and the body has no expression, but is still a valid lambda expression.

(int x, int y) -> { return x + y; } 
(int x, int y) -> return x + y; //both are valid since the body only contains one expressio.

最后的这个例子只是表示可以这么写,但实际情况中并不推荐。: )
(List<Integer> x) -> {int min = x.get(0); for (int i = 1; i < x.size(); i++) if (x.get(i) < min) min = x.get(i); System.out.println(min); }
//lambda here!
listDevs.sort((Developer o1, Developer o2)->o1.getAge()-o2.getAge());
//lambda
listDevs.sort((Developer o1, Developer o2)->o1.getAge()-o2.getAge());

//lambda, valid, parameter type is optional
listDevs.sort((o1, o2)->o1.getAge()-o2.getAge());

//sort by name
Collections.sort(listDevs, new Comparator<Developer>() {
    @Override
    public int compare(Developer o1, Developer o2) {
        return o1.getName().compareTo(o2.getName());
    }
});

//lambda
listDevs.sort((Developer o1, Developer o2)->o1.getName().compareTo(o2.getName()));

//lambda
listDevs.sort((o1, o2)->o1.getName().compareTo(o2.getName()));

//3.4.2 Lambda expression to sort a List using their salary, reversed order.
Comparator<Developer> salaryComparator = (o1, o2)->o1.getSalary().compareTo(o2.getSalary());
listDevs.sort(salaryComparator.reversed());

Sort objects on multiple fields /properties

list.sort((o1, o2) -> {
    int cmp = o1.getGroup().compareTo(o2.getGroup());
    if (cmp == 0)
        cmp = Integer.compare(o1.getAge(), o2.getAge());
    if (cmp == 0)
        cmp = o1.getName().compareTo(o2.getName());
    return cmp;
});


class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> count = new HashMap();
        for (String word: words) {
            count.put(word, count.getOrDefault(word, 0) + 1);
        }
        List<String> candidates = new ArrayList(count.keySet());
        Collections.sort(candidates, (w1, w2) -> count.get(w1) != count.get(w2) ?
                count.get(w2) - count.get(w1) : w1.compareTo(w2));

        return candidates.subList(0, k);
        }
    }

results matching ""

    No results matching ""