如何在使用Java 8运行时在流中获取新用户输入

问题描述 投票:1回答:1

我需要验证用户输入,如果它不符合条件,那么我需要用正确的输入替换它。到目前为止,我被困在两个部分。我是java8的新手,并不熟悉所有的库,所以如果你能给我建议在哪里阅读更多这些我会很感激。

List<String> input = Arrays.asList(args);
List<String> validatedinput = input.stream()
   .filter(p -> {
       if (p.matches("[0-9, /,]+")) {
           return true;
       }
       System.out.println("The value has to be positve number and not a character");
       //Does the new input actually get saved here?
       sc.nextLine();
       return false;
   }) //And here I am not really sure how to map the String object
   .map(String::)
   .validatedinput(Collectors.toList());
java-8 java-stream
1个回答
1
投票

这种类型的逻辑不应该用流完成,while循环将是它的一个很好的候选者。

首先,让我们将数据分成两个列表,一个表示有效输入,另一个表示无效输入:

Map<Boolean, List<String>> resultSet =
            Arrays.stream(args)
                    .collect(Collectors.partitioningBy(s -> s.matches(yourRegex), 
                                 Collectors.toCollection(ArrayList::new)));

然后创建while循环以要求用户更正所有无效输入:

int i = 0;
List<String> invalidInputs = resultSet.get(false);
final int size = invalidInputs.size();    
while (i < size){
     System.out.println("The value --> " + invalidInputs.get(i) +
             " has to be positive number and not a character");
     String temp = sc.nextLine();
     if(temp.matches(yourRegex)){
         resultSet.get(true).add(temp);
         i++;
     }
}

现在,您可以收集所有有效输入的列表,并使用它执行您喜欢的操作:

List<String> result = resultSet.get(true);
© www.soinside.com 2019 - 2024. All rights reserved.