如何在字符串列表中使用 startsWith 和 contains 方法

huangapple go评论70阅读模式
英文:

How to use startsWith and contains within a List of String

问题

我有这个实现,我需要检查基于接受的版本列表,以确定是否接受具有x.x.x格式的版本。例如,如果1.3在接受的版本列表中,那么1.3.1、1.3.2或简单地1.3.x都是被接受的。如果1.2不在列表中,那么1.2.x就不被接受。

@Test
public test() {
    Assert.assertTrue(isVersionAccepted("1.3.2"));
    Assert.assertFalse(isVersionAccepted("1.2.1"));
}

public static boolean isVersionAccepted(String version) {
    List<String> acceptedVersions = Arrays.asList("1.1", "1.3", "1.5", "2.5", "2.7", "3.1", "3.2");

    // 处理
}
英文:

i have this implementation that I need to check whether the version with x.x.x format is accepted based on accepted version in the list with just a format of x.x.

For example, if 1.3 is in the accepted version list. then 1.3.1, 1.3.2 or simply 1.3.x is accepted. As if 1.2 is not in the list then 1.2.x is not accepted.

 @Test 
 public test() {
     Assert.assertTrue(isVersionAccepted(&quot;1.3.2&quot;));
     Assert.assertFalse(isVersionAccepted(&quot;1.2.1&quot;));
 }

 public static boolean isVersionAccepted(String version) {
        List&lt;String&gt; acceptedVersions = Arrays.asList(&quot;1.1&quot;, &quot;1.3&quot;, &quot;1.5&quot;, &quot;2.5&quot;, &quot;2.7&quot;, &quot;3.1&quot;, &quot;3.2&quot;);
         
       // process
        
 }

答案1

得分: 0

你可以使用 Stream#anyMatch 来检查输入是否以 List 中的任何值开头。

return acceptedVersions.stream().anyMatch(version::startsWith);
英文:

You can use Stream#anyMatch to check if the input starts with any of the values in the List.

return acceptedVersions.stream().anyMatch(version::startsWith);

huangapple
  • 本文由 发表于 2023年2月18日 09:14:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75490570.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定