Java8 FP if / else if / else用lambdas替换

时间:2018-09-15 14:36:20

标签: java lambda functional-programming

我对Java 8 if语句有疑问。如果不使用Java 8 lambda,有人可以向我展示一种编写此代码的方法吗? 解决方案不应包含if,while或for。甚至有可能吗?

JTable replacedAssets = new JTable(...);
replacedAssets.addMouseListener ( new MouseAdapter ( ) {
        @Override
        public void mouseClicked ( MouseEvent e ) {
            super.mouseClicked ( e );
            if ( e.getClickCount () == 2 ) {
                rowIndex = replacedAssets.getSelectedRow ();
                columnIndex = replacedAssets.getSelectedColumn ();
                if ( rowIndex == 0 && ( columnIndex == 1 || columnIndex == 2 ) ) {
                    initial = replacedAssets.getValueAt ( rowIndex , columnIndex );
                    JOptionPane.showMessageDialog ( parent , "Editing this Field may cause error in the data causing problems." , "Error Edit Not Permitted For This Field" , JOptionPane.ERROR_MESSAGE );
                }
            }
        }
    } );

2 个答案:

答案 0 :(得分:6)

没有“ if,while或for”,但也没有lambda:

return (first_number == second_number ? "PERFECT" :
        first_number > second_number ? "ABUNDANT" : "DEFICIENT");

? :在Java语言规范中称为条件运算符(请参见15.25. Conditional Operator ? :),但通常称为三元运算符 ,因为它是Java中唯一由三部分组成的运算符。

答案 1 :(得分:0)

使用lambdas解决方案如何?我假设使用整数值,但切换到float或double并不难。

^[a].*[a]$|^[e].*[e]$|^[i].*[i]$|^[o].*[o]$|^[u].*[u]$

编辑:Andreas提到了有效的担忧,我同意您不会那样做。但我认为,更多的是证明可以使用lambda。 :)另一种方法(ab)使用可选:

    int first_number = 10;
    int second_number = 20;
    IntBinaryOperator subtract = (n1, n2) -> n1 - n2; // Subtract second from first value
    IntUnaryOperator determineSign = n -> Integer.signum(n); // Determine the sign of the subtraction
    IntFunction<String> message = key -> { // Sign of 0 means value has been 0 (first_number == second_number). Sign of 1 = positive value, hence equals first_number > second_number, otherwise return the default.
        Map<Integer, String> messages = new HashMap<>();
        messages.put(0, "PERFECT");
        messages.put(1, "ABUNDANT");
        return messages.getOrDefault(key, "DEFICIENT");
    };

     return message.apply(determineSign.applyAsInt(subtract.applyAsInt(first_number, second_number)));