[英]Get distinct elements from java string array
我有一個字符串數組,如下所示。
String [] exmp = {"Example ExamPle", "Example"};
無論字符大小寫如何,我都想從上述數組中獲取不同的元素。
我需要為上面的數組獲取下面的 output。 “例子”
我已嘗試使用以下代碼。
LinkedHashSet<String> set = new LinkedHashSet<String>();
String [] exmp = {"Example ExamPle", "Example"};
for(String s : exmp) {
String unqWrds = Arrays.stream(s.split("\\s+")).distinct().collect(Collectors.joining(" "));
set.add(unqWrds);
}
但目前由於大小寫差異“Example Example”,“Example”,我正在將整個字符串添加到集合中
你能在這里建議嗎。
根據問題中的示例代碼,您希望在空格上拆分字符串,即使您從未在問題中說過。
然后您嘗試使用distinct()
,但不幸的是這不起作用,因為distinct()
不采用Comparator
,因此它不能不區分大小寫進行比較。
要獲得您想要的結果:
// Using loops
public static Set<String> distinctWords(String... input) {
Set<String> distinct = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
for (String s : input)
for (String word : s.trim().split("\\s+"))
distinct.add(word);
return distinct;
}
// Using streams
public static Set<String> distinctWords(String... input) {
return Stream.of(input)
.flatMap(s -> Stream.of(s.split("\\s+")))
.collect(Collectors.toCollection(() -> new TreeSet<>(String.CASE_INSENSITIVE_ORDER)));
}
TreeSet
將保留第一個單詞的大小寫,並對單詞進行排序,因此使用{"Example ExamPle", "example"}
調用的結果是所需的結果[Example]
。
試試看:
String unqWrds = Arrays.stream(s.split("\\s+")).reduce("", (x, y) -> x.toUpperCase().contains(y.toUpperCase()) ? x : x + " " + y);
忽略大小寫部分可以這樣完成:
String unqWrds = Arrays.stream(s.split("\\s+")).map(String::toLowerCase).distinct().collect(Collectors.joining(" "));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.