[英]How to check the length of multiple String using HashSet
我有6個單詞存儲在HashSet
,如下所示:
String first = jtfFirstWord.getText();
String second = jtfSecondWord.getText();
String third = jtfThirdWord.getText();
String fourth = jtfFourthWord.getText();
String fifth = jtfFifthWord.getText();
String sixth = jtfSixthWord.getText();
Set<String> accept = new HashSet<String>(Arrays.asList(new String[] {first,second,third,fourth,fifth,sixth}));
我想檢查所有單詞的長度是否不是7、9或11,然后我將在消息框提示用戶警告他們僅輸入7、9或11個字符的單詞。
當前,我正在使用if-else語句來手動檢查條件,例如:
if (first.length() != 7 || first.length() != 9 || first.length() != 11 ||
second.length() != 7 ||second.length() != 9 || second.length() != 11 ||
... and it continues until the sixth word.
通過這種方式,它降低了我的代碼的可讀性,並且不是檢查用戶輸入的好方法。
我的問題是如何檢查上面存儲在HashSet中的String元素的長度? 還是有其他優雅而有效的方式來檢查輸入?
當然,您可以使用循環,檢查集合中的每個元素是否具有可接受的長度之一,並在沒有一個字符串的情況下立即退出循環。
但是您也可以使用Stream的allMatch方法,該方法可以為您完成此操作:
boolean allOK = accept.stream().allMatch(s ->
s.length() == 7 || s.length() == 9 || s.length() == 11);
if (!allOK) {
// display error message
}
如果您使用的是Java 8,則可以使用Stream::allMatch
boolean check = accept.stream()
.allMatch(input -> Arrays.asList(7, 9, 11).contains(input.length()));
要么 :
List<Integer> acceptedLengths = Arrays.asList(7, 9, 11);
boolean check = accept.stream()
.allMatch(input -> acceptedLengths.contains(input.length()));
我使用Arrays.asList(7, 9, 11)
定義了可接受的長度,您可以在此處添加所需的內容,這比對每個長度使用條件要容易得多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.