我在使用a List及其stream()方法时遇到了一个问题.虽然我知道如何使用它们,但我不确定何时使用它们.
例如,我有一个列表,包含到不同位置的各种路径.现在,我想检查一个给定路径是否包含列表中指定的任何路径.我想boolean根据条件是否得到满足返回.
当然,这本身并不是一项艰巨的任务.但我想知道我是应该使用流还是使用for(-each)循环.
列表
private static final List<String> EXCLUDE_PATHS = Arrays.asList(new String[]{
"my/path/one",
"my/path/two"
});
Run Code Online (Sandbox Code Playgroud)
示例 - 流
private boolean isExcluded(String path){
return EXCLUDE_PATHS.stream()
.map(String::toLowerCase)
.filter(path::contains)
.collect(Collectors.toList())
.size() > 0;
}
Run Code Online (Sandbox Code Playgroud)
示例 - For-Each循环
private boolean isExcluded(String path){
for (String excludePath : EXCLUDE_PATHS) {
if(path.contains(excludePath.toLowerCase())){
return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
请注意,path参数始终为小写.
我的第一个猜测是for-each方法更快,因为如果条件满足,循环将立即返回.而流仍将循环遍历所有列表条目以完成过滤.
我的假设是否正确?如果是这样,为什么(或者更确切地说)何时使用stream()?
这是我的Interface ClassA .java
@Path("/"+Paths.STORIES)
@ApiModel(value = "Name API")
@Api(value = "/stories", description = "Name API")
public interface ClassA {
@GET
@Path("/"+Paths.STORYID)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Fetch Story by ID", notes = "More notes about this method")
@ApiResponses(value = {
@ApiResponse(code = 400, message = "Invalid ID supplied"),
@ApiResponse(code = 200, message = "Invalid ID supplied"),
})
public Response getNameFromID(@PathParam("nameId") String nameId);
}
Run Code Online (Sandbox Code Playgroud)
这是我的实现类.
@Singleton
@Component
public class ClassB implements ClassA,InitializingBean{
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Response getNameFromID(final String nameId) { …Run Code Online (Sandbox Code Playgroud) 是不是可能在一个线程中的wait()之前调用另一个线程中的notify()?它发生在我身上.
客户端从目标请求值并等待结果变量RV.如果目标是客户端本身,我使用正确的结果更新RV并在另一个线程中调用RV上的notify().
class EMU {
ResultVar RV;
Address my_address;
ResultVar findValue(String key) {
String tgt = findTarget(key);
sendRequest(tgt, key);
synchronized(RV) {
RV.wait();
}
return RV;
}
Runnable Server = new Runnable() {
public void run() {
//code to receive connections. Assume object of type Request is read from the stream.
Request r = (Request) ois.readObject();
if(r.requesterAddr.compareTo(my_address) == 0) {
String val = findVal(key);
RV.putVal(val);
synchronized(RV){
RV.notify();
}
}
}
};
}
Run Code Online (Sandbox Code Playgroud)
问题是在请求者自己完成所有"网络"(上例中的sendReqest)之前,结果会在结果变量中更新.当请求者线程现在调用wait()时,程序不会继续,因为已经调用了notify.
我们怎样才能防止它呢?