[英]Shortest code to check condition inside for-loop
What is the shortest form for this code? 该代码的最短形式是什么?
List<String> supported = Arrays.asList("...");
boolean isSupported = false;
for(String s : supported) {
if(url.startsWith(s)) {
isSupported = true;
break;
}
}
Or this is the shortest form to check condition inside a for-loop ? 还是这是检查for循环内条件的最短形式?
如果您使用的是Java 8,则可以在Stream API的帮助下一行完成此操作:
boolean isSupported = supported.stream().anyMatch(s -> url.startsWith(s));
The Java 8 answer given by @Azel +1 is lean and is probably the best answer that can be given with your current design. @Azel +1给出的Java 8答案很苗条,可能是您当前设计中可以给出的最佳答案。 However, I have had similar problems to yours in the past, and have found it better to identify URLs by their hosts, rather than just by an arbitrary beginning substring.
但是,我过去遇到过与您类似的问题,并且发现更好的方法是通过主机识别URL,而不仅仅是通过任意的开始子字符串识别URL。 What I ended up doing was to create a map of hosts.
我最终要做的是创建主机映射。 Then, I compared each incoming URL against that
Map
, something like this: 然后,我将每个传入的URL与该
Map
,如下所示:
Map<String, Integer> hosts = new HashMap<>();
hosts.add("google.com", 1);
hosts.add("stackoverflow.com", 1);
hosts.add("wordpress.com", 1);
URL url = new URL("http://www.google.com");
String host = url.getHost();
if (hosts.containsKey(host)) {
System.out.println("Found " + url + " in list of approved hosts.");
}
The basic idea here is that we don't even need to iterate a list of approved domains, we can just do a constant time lookup against a whitelist (or maybe blacklist). 这里的基本思想是,我们甚至不需要迭代已批准域的列表,我们只需针对白名单(或黑名单)进行恒定时间查找即可。
In practice, you might use a Java properties file to store the list of known hosts, and then load it when you need it. 实际上,您可以使用Java属性文件存储已知主机的列表,然后在需要时加载它。
This is the shortest for array 这是最短的数组
boolean isSupported = false;
for(String s : supported)
if(isSupported = url.startsWith(s)) break;
You can create a method to make it easier. 您可以创建一种方法来简化它。 I'm assuming you're using an array, but this will also work with a list.
我假设您正在使用数组,但这也可以用于列表。
boolean containsURL(String[] array, URL url) {
for (String s : array)
if (url.startsWith(s))
return true;
return false;
}
isSupported = containsURL(supported, url);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.