问题描述
我想过滤Person类的列表,最后使用Streams映射到Java中的一些匿名类。我能够在C#中轻松完成同样的事情。
I wanted to filter list of Person class and finally map to some anonymous class in Java using Streams. I am able to do the same thing very easily in C#.
人员类
class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
以希望格式映射结果的代码。
Code to map the result in desire format.
List<Person> lst = new List<Person>();
lst.Add(new Person() { Name = "Pava", Address = "India", Id = 1 });
lst.Add(new Person() { Name = "tiwari", Address = "USA", Id = 2 });
var result = lst.Select(p => new { Address = p.Address, Name = p.Name }).ToList();
现在,如果我想访问新创建类型的任何属性,我可以使用下面提到的语法轻松访问。
Now if I wanted to access any property of newly created type I can easily access by using below mentioned syntax.
Console.WriteLine( result[0].Address);
理想情况下,我应该使用循环来迭代结果。
Ideally I should use loop to iterate over the result.
我知道在java中我们收集了ToList并映射了Select。
但是我无法只选择Person类的两个属性。
我该怎么做Java
I know that in java we have collect for ToList and map for Select.But i am unable to select only two property of Person class.How can i do it Java
推荐答案
好吧,你可以映射人
实例到匿名类的实例,例如假设
Well, you can map Person
instances to instances of anonymous classes, e.g. assuming
class Person {
int id;
String name, address;
public Person(String name, String address, int id) {
this.id = id;
this.name = name;
this.address = address;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
}
你能做什么
List<Person> lst = Arrays.asList(
new Person("Pava", "India", 1), new Person("tiwari", "USA", 2));
List<?> result = lst.stream()
.map(p -> new Object() { String address = p.getAddress(); String name = p.getName(); })
.collect(Collectors.toList());
但是你可能会注意到,它不是那么简洁,而且更重要的是,结果
变量不能引用匿名类型,这使得匿名类型的实例几乎无法使用。
but as you might note, it’s not as concise, and, more important, the declaration of the result
variable can’t refer to the anonymous type, which makes the instances of the anonymous type almost unusable.
目前,lambda表达式是唯一支持声明隐含类型变量的Java功能,它可以是匿名的。例如,以下方法可行:
Currently, lambda expressions are the only Java feature that supports declaring variables of an implied type, which could be anonymous. E.g., the following would work:
List<String> result = lst.stream()
.map(p -> new Object() { String address = p.getAddress(); String name = p.getName(); })
.filter(anon -> anon.name.startsWith("ti"))
.map(anon -> anon.address)
.collect(Collectors.toList());
这篇关于什么相当于JAVA的流API中的C#的Select子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!