我无法按内容对列表中的元素进行分组。我们有以下列表:
67 = "6.1"
68 = "6.1.1"
69 = "6.1.2"
70 = "6.1.3"
71 = "6.1.4"
72 = "6.1.5"
73 = "6.2"
74 = "6.2.1"
75 = "6.2.2"
76 = "6.2.3"
77 = "6.2.4"
78 = "6.2.5"
79 = "6.2.6"
80 = "6.2.7"
81 = "6.2.9"
82 = "6.2.10"
83 = "6.2.12"
84 = "6.2.13"
85 = "6.2.14"
86 = "6.2.15"
87 = "6.2.16"
88 = "6.2.18"
89 = "6.2.19"
90 = "6.2.20"
91 = "6.2.21"
92 = "6.3"
93 = "6.3.1"
94 = "6.3.2"
95 = "6.3.3"
96 = "6.3.4"
97 = "6.4"
98 = "6.4.2"
99 = "6.4.3."
如何找到所有元素,例如6.2 => 6.2.x中?
private static void filterNumbers(List<String> numbers) {
for (int i = 0; i < numbers.size(); i++) {
final int index = i;
List<String> result = numbers.stream().filter(n -> n.contains(numbers.get(index))).collect(Collectors.toList());
System.out.println();
}
}
答案 0 :(得分:1)
我没有JDK 8来测试这个,我不习惯Stream
,但我想你可以这样编写你的解决方案:
// Predicate is "6.2"
private static List<String> filterNumbers(List<String> numbers, String predicate) {
return numbers.stream().filter(n -> n.equals(predicate) || n.startsWith(predicate + '.')).collect(Collectors.toList());
}
如果你想要向后兼容或者只是对Stream
不放心,你仍然可以使用String.startsWith(String)
去上学(并为普通开发人员提供易读性):< / p>
private static List<String> filterNumbers(List<String> numbers, String predicate) {
List<String> filtered = new ArrayList<>();
for (String n : numbers) {
if (n.equals(predicate) || n.startsWith(predicate + '.')) {
filtered.add(number);
}
}
return filtered;
}
注意到John Kuhns,nb.startsWith("6.2")
将返回"6.2"
,"6.2.1"
,还会"6.20"
。
为避免这种情况,您应该将测试调整为nb.equals("6.2") || nb.startsWith("6.2.")
。
Regex被认为是一种潜在的解决方案。
我爱他们,他们是强大的,但如果你能避免他们,那就去做吧!它们不是Java最有效的功能(虽然我对此的了解可能会变老)。另外,我知道许多开发人员遇到困难时会感到困惑。