我需要使用特定对象的属性(Location)对对象列表(Student)进行分组,代码如下所示,
public class Grouping {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
List<Student> studlist = new ArrayList<Student>();
studlist.add(new Student("1726", "John", "New York"));
studlist.add(new Student("4321", "Max", "California"));
studlist.add(new Student("2234", "Andrew", "Los Angeles"));
studlist.add(new Student("5223", "Michael", "New York"));
studlist.add(new Student("7765", "Sam", "California"));
studlist.add(new Student("3442", "Mark", "New York"));
//Code to group students by location
/* Output should be Like below
ID : 1726 Name : John Location : New York
ID : 5223 Name : …Run Code Online (Sandbox Code Playgroud) 声纳告诉我"用方法参考替换这个lambda"
public class MyClass {
private List<SomeValue> createSomeValues(List<Anything> anyList) {
return anyList //
.stream() //
.map(anything -> createSomeValue(anything)) //
.collect(Collectors.toList());
}
private SomeValue createSomeValue(Anything anything) {
StatusId statusId = statusId.fromId(anything.getStatus().getStatusId());
return new SomeValue(anything.getExternId(), statusId);
}
}
Run Code Online (Sandbox Code Playgroud)
这可能吗?我尝试了几件事,比如
.map(MyClass::createSomeValue) //
Run Code Online (Sandbox Code Playgroud)
但我需要将方法更改为静态.而且我不是静态方法的忠实粉丝.
SonarQube的解释是:
方法/构造函数引用比使用lambdas更紧凑和可读,因此是首选.
我编写了代码,从包含Date变量的对象列表中查找最新日期.
list.stream().map(segment -> segment.lastLoad).filter(x->x!=null).max(Date::compareTo).get()
但我得到了声纳问题
用方法引用'Objects :: nonNull'替换这个lambda.
我无法弄清楚的是我在哪里可以使用声纳lint问题所述的方法参考.