如何使用Java流和Lambda函数创建if~elseif语句?

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

How to make if~elseif statement using by Java stream and lambda function?

问题

import java.util.Scanner;
import java.util.function.Consumer;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("score : ");
        int score = sc.nextInt();

        Consumer<String> printGrade = grade -> System.out.println(grade);

        IntStream.rangeClosed(0, 10)
                .map(i -> 10 - i)
                .filter(i -> score / 10 >= i)
                .findFirst()
                .ifPresent(i -> {
                    switch (i) {
                        case 10:
                        case 9:
                            printGrade.accept("A");
                            break;
                        case 8:
                            printGrade.accept("B");
                            break;
                        case 7:
                            printGrade.accept("C");
                            break;
                        case 6:
                            printGrade.accept("D");
                            break;
                        default:
                            printGrade.accept("F");
                    }
                });
    }
}
英文:

I want to make grade program like below.

But I must do not use if~else statement.

Must use Java Stream and lambda function.

public static void main(String[] args) {
   Scanner sc = new Scanner(System.in);
   System.out.println(&quot;score : &quot;);
   int score = sc.nextInt();

   switch(score/10) {
		case 10:
		case 9:
			System.out.println(&quot;A&quot;);
			break;
		case 8:
			System.out.println(&quot;B&quot;);
			break;
		case 7:
			System.out.println(&quot;C&quot;);
			break;
		case 6:
			System.out.println(&quot;D&quot;);
			break;
		default :
			System.out.println(&quot;F&quot;);
		}
}

答案1

得分: 2

Stream比条件语句更像一个循环结构。由于一个阶段的结果可以链接到另一个阶段,它们需要在从一个阶段传递到另一个阶段时保持对象结构的统一性。因此,我认为没有办法将if-else语句编写为单独的阶段。然而,您可以将它们包装在一个map内,并进行条件工作。

public static void main(String[] args) {
   Arrays.stream(args)
   .map(Integer::parseInt)
   .forEach(score -> {
      switch(score/10) {
        case 10:
        case 9:
            System.out.println("A");
            break;
        case 8:
            System.out.println("B");
            break;
        case 7:
            System.out.println("C");
            break;
        case 6:
            System.out.println("D");
            break;
        default :
            System.out.println("F");
        }
   });
}
英文:

Stream is more of a looping construct than a conditional construct. And since the outcomes of one stage can be chained to another, they need to maintain uniformity in the object structure to be passed from one to the other.
So, I don't think there is a way to write if-else statements as separate stages.
However, you can wrap them inside a map and do the conditional work.

public static void main(String[] args) {
   Arrays.stream(args)
   .map(Integer::parseInt)
   .forEach(score =&gt; {
      switch(score/10) {
        case 10:
        case 9:
            System.out.println(&quot;A&quot;);
            break;
        case 8:
            System.out.println(&quot;B&quot;);
            break;
        case 7:
            System.out.println(&quot;C&quot;);
            break;
        case 6:
            System.out.println(&quot;D&quot;);
            break;
        default :
            System.out.println(&quot;F&quot;);
        }
   })
}

</details>



# 答案2
**得分**: 1

以下是翻译好的代码部分:

```java
public class App {

    static class Grade {
        private final String grade;
        private final Integer score;

        public Grade(String grade, Integer score) {
            this.grade = grade;
            this.score = score;
        }

        public String getGrade() {
            return grade;
        }

        public Integer getScore() {
            return score;
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("分数:");
        int score = sc.nextInt();
        List<Grade> gradeList = new ArrayList<>();
        gradeList.add(new Grade("A", 9));
        gradeList.add(new Grade("B", 8));
        gradeList.add(new Grade("C", 7));
        gradeList.add(new Grade("D", 6));

        Grade s = gradeList.stream()
                .filter(el -> (score / 10) >= el.getScore())
                .findFirst().orElse(new Grade("F", 5));
        System.out.println(s.getGrade());
    }
}
英文:

You can use this solution:

public class App {

    static class Grade {
        private final String grade;
        private final Integer score;

        public Grade(String grade, Integer score) {
            this.grade = grade;
            this.score = score;
        }

        public String getGrade() {
            return grade;
        }

        public Integer getScore() {
            return score;
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println(&quot;score : &quot;);
        int score = sc.nextInt();
        List&lt;Grade&gt; gradeList = new ArrayList&lt;&gt;();
        gradeList.add(new Grade(&quot;A&quot;, 9));
        gradeList.add(new Grade(&quot;B&quot;, 8));
        gradeList.add(new Grade(&quot;C&quot;, 7));
        gradeList.add(new Grade(&quot;D&quot;, 6));

        Grade s = gradeList.stream()
                .filter(el -&gt; ( score / 10 ) &gt;= el.getScore())
                .findFirst().orElse(new Grade(&quot;F&quot;, 5));
        System.out.println(s.getGrade());
    }
}

huangapple
  • 本文由 发表于 2020年9月4日 03:30:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63730475.html
匿名

发表评论

匿名网友

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

确定