本文介绍了Java中的Lambda表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将部分项目从C#切换到Java。但是在此之前,我想仔细地和完全地比较两种语言。

I need to switch part of my projects from C# to Java. But before which, I would like to compare two languages carefully and completely.

关于lambda表达式,我可以通过C#编写非常优雅的代码,问题是如何实现Java中相同的功能?

Regarding to lambda expression, I could write very elegant code via C#, the question is how to implement the same feature gracefully in Java? Thanks in advance!

class Program
{
    enum Gender
    {
        Male,
        Female
    }
    class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public Gender Gender { get; set; }
        public override string ToString()
        {
            return string.Format("Id: {0}, Name: {1}, Age: {2}, Gender: {3}", Id, Name, Age, Gender);
        }
    }

    static void Main(string[] args)
    {
        var students = new[] {
            new Student { Id = 1, Name = "Nathanial Archibald", Age = 18, Gender = Gender.Male },
            new Student { Id = 2, Name = "Georgina Sparks", Age = 19, Gender = Gender.Female },
            new Student { Id = 3, Name = "Daniel Humphrey", Age = 20, Gender = Gender.Male },
            new Student { Id = 4, Name = "Jenny Humphrey", Age = 17, Gender = Gender.Female },
        };

        var men = students.Where(p => p.Gender == Gender.Male);
        var ageAbove18 = students.Where(p => p.Age > 18);
        var humphrey = students.Where(p => p.Name.EndsWith("Humphrey"));
        var idGT1orderbyAge = students.Where(p => p.Id > 1).OrderBy(p => p.Age);

        foreach (var s in men) Console.WriteLine(s.ToString());
        foreach (var s in ageAbove18) Console.WriteLine(s.ToString());
        foreach (var s in humphrey) Console.WriteLine(s.ToString());
        foreach (var s in idGT1orderbyAge) Console.WriteLine(s.ToString());
    }
}


推荐答案

Java在版本8中可能支持lambda。)

Java in version 8 might support lambda.;)

您可以使用此或。
参见以下示例:

You can use this Site or this.See this example:

final Array<Integer> a = array(1, 2, 3);
final Array<Integer> b = a.map({int i => i + 42});
arrayShow(intShow).println(b); // {43,44,45}

这篇关于Java中的Lambda表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:46