我有一个包含一些User对象的列表,我正在尝试对列表进行排序,但只能使用方法引用,使用lambda表达式,编译器会给出错误:
List<User> userList = Arrays.asList(u1, u2, u3);
userList.sort(Comparator.comparing(u -> u.getName())); // works
userList.sort(Comparator.comparing(User::getName).reversed()); // works
userList.sort(Comparator.comparing(u -> u.getName()).reversed()); // Compiler error
Run Code Online (Sandbox Code Playgroud)
错误:
com\java8\collectionapi\CollectionTest.java:35: error: cannot find symbol
userList.sort(Comparator.comparing(u -> u.getName()).reversed());
^
symbol: method getName()
location: variable u of type Object
1 error
Run Code Online (Sandbox Code Playgroud) 在下面的代码中,它在使用类名传递方法引用变量时起作用,但是当使用用户对象传递引用变量时会出现错误.
public class User {
private String name;
public User(String name) {
this.name = name;
}
public void printName() {
System.out.println(name);
}
}
public class Main {
public static void main(String[] args) {
User u1 = new User("AAA");
User u2 = new User("BBB");
User u3 = new User("ZZZ");
List<User> userList = Arrays.asList(u1, u2, u3);
userList.forEach(User::printName); // works
userList.forEach(u1::printName); // compile error
}
}
Run Code Online (Sandbox Code Playgroud) 我正在使用lambda表达式进行一些测试,但我的代码不能编译.我的lambda实现是错误的还是异常处理?以下代码的正确实现是什么?
class MyObject { }
interface Creatable<T> {
T create() throws IOException;
}
/* Using the code: */
Creatable<MyObject> creator = () -> {
try {
return new MyObject();
} catch (IOException e) {
e.printStackTrace();
}
};
MyObject obj1 = creator.create();
Run Code Online (Sandbox Code Playgroud)
如果我删除try catch块并声明抛出该方法的异常,代码将编译并正常运行.
Creatable<MyObject> creator = () -> new MyObject();
Run Code Online (Sandbox Code Playgroud)
编译错误是:
incompatible types: bad return type in lambda expression
我有Flyweight模式,我尝试将循环转换为流,但结果是不同的:
public Line getLine(Color color) {
for(Line line: pool) {
if(line.getColor().equals(color)) {
return line;
}
}
return createLine(color);
}
factory.getLine(Color.RED);
factory.getLine(Color.RED);
System.out.println(getPool().size()); // print 1
Run Code Online (Sandbox Code Playgroud)
重构代码:
public Line getLine(Color color) {
return pool.stream()
.filter(l -> l.getColor().equals(color))
.findFirst()
.orElse(createLine(color));
}
factory.getLine(Color.RED);
factory.getLine(Color.RED);
System.out.println(getPool().size()); // print 2
Run Code Online (Sandbox Code Playgroud)
流有什么问题?
我正在将JanusGraph与Gremlin一起使用,并且此数据集包含2.6k节点和6.6k边(两侧为3.3k边)。我已经运行查询10分钟,没有找到最短的路径。
使用Gephi,最短路径几乎是瞬时的。
这是我的查询:
g.V(687).repeat(out().simplePath()).until(hasId(1343)).path().limit(1)
Run Code Online (Sandbox Code Playgroud) java ×4
java-8 ×4
lambda ×3
cassandra ×1
for-loop ×1
graph ×1
gremlin ×1
janusgraph ×1
java-stream ×1