Reputation: 793
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.
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());
}
}
Upvotes: 6
Views: 3304
Reputation: 822
Java 8 supports Lambda expression. Here is how you can use lambda expression in java to sort a list of Students
private static void sort(List<Student> students) {
Comparator<Student> rollNumberComparator = (student1, student2) ->
student1.getRollNumber().compareTo(student2.getRollNumber());
Collections.sort(students,rollNumberComparator);
}
You can refer : http://www.groupkt.com/post/088a8dea/lambda-expressions---java-8-feature.htm
Upvotes: 1
Reputation:
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}
Upvotes: 3
Reputation: 3026
Currently java doesn't support Lambda operation, but this will going to be introduced in Java 8. For further reference site
But as you want to switch to Java this is a good option but as long as lambda operation is not supported you can create your methods to do the same task and after java 8 release shift to the lambha operation
here is an example of lambha operation in java 8
Upvotes: 3
Reputation: 17422
Lambda expressions aren't part of the current version of Java (1.7) it is a feature for Java 8, which wont be released at least until next year
Upvotes: 0