使用Java-8中的函数的ArrayList [英] Working with an ArrayList of Functions in Java-8

查看:142
本文介绍了使用Java-8中的函数的ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题描述:
我希望能够使用从另一个类(在其他类中定义的函数)中传入的函数的ArrayList。如果在一个类中定义了可能具有不同输入和返回类型的函数列表,我希望能够将其中某些类的ArrayList传递给其他类的构造函数或方法使用它们执行操作。

代码描述:
下面的代码是一个非常简化的例子,从设计的角度来看,这并不是很有意义。问题的焦点是 SomeClass 中的方法 getResult(),并且一般如何使用函数的ArrayList有它们。

尝试解决问题:
getResult()方法实现是许多尝试使用功能列表。再次,请不要介意代码的设计。正是通过这种方式来尽可能缩短问题范例。

简单的测试人员类

  package com.Testing; 

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.Function;

public class Tester {

public static void main(String [] args)
{
//某些函数
函数< Integer ,整数>增量=(整数输入) - > {
返回输入+ 1;
};

函数<整数,整数>递减=(整数输入) - > {
return input - 1;
};

功能< Double,Double> timesPi =(双输入) - > {
返回输入* 3.14;
};

//函数列表
List< Function> availableMathOperations = new ArrayList<>();
列表<函数> selectedMathOperations = new ArrayList<>();

//填充主列表
availableMathOperations.add(increment);
availableMathOperations.add(decrement);
availableMathOperations.add(timesPi);

//填充随机选择列表//
//生成随机二进制数
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(availableMathOperations.size()* 2);
boolean [] bits = new boolean [availableMathOperations.size()]; (int j = 0; j< availableMathOperations.size(); j ++){
bits [availableMathOperations.size() - 1 - j] =(1 << j& randomNumber )!= 0;
}

//将数学运算添加到基于二进制数的selectedMathOperations
for(int j = 0; j if (bits [j]){
selectedMathOperations.add(availableMathOperations.get(j));
}
}

SomeClass someClass = new SomeClass(s​​electedMathOperations,1.23);



其他课程

  package com.Testing; 

import java.util.List;
import java.util.function.Function;

public class SomeClass {

List< Function>操作;
double initialValue;

public SomeClass(List< Function> newOperations,double newInitialValue){
operations = newOperations;
initialValue = newInitialValue;
}

public double getResult(){
double result = 0.0;

//问题方法
//使用最初的初始值执行随机操作列表
for(int i = 0; i< operations.size(); i ++ ){
if(i == 0)
result = operations.get(i)(initialValue);
else
result + = operations.get(i)(result);
}
返回结果;
}

}


解决方案

方法 .htmlrel =noreferrer> java.util.function.Function 对象是 apply 。您需要像这样调用它:

  operations.get(i).apply(initialValue)

然而,您使用raw Function ,因此结果可能是 Object ,您需要将其转换为适当的类型。此外,您不能使用 + (或 + = )运算符。我建议使用 Number 限制参数类型:

  List<函数<数量,?扩展Number>> operations = Arrays.asList(
num - > num.intValue()+ 1,
num - > num.intValue() - 1,
num - > num.doubleValue )* 3.14
); //只是一个例子列表

public double getResult(){
double result = 0.0;

for(int i = 0; i< operations.size(); i ++){
if(i == 0){
result = operations.get(i )。适用(初值).doubleValue();
} else {
result + = operations.get(i).apply(result).doubleValue();
}
}
返回结果;
}


Problem Description: I want to be able to use an ArrayList of Functions passed in from another class (where the Functions have been defined in that other class). If the list of Functions, which may have different input and return types, are defined in one class, I want to be able to pass an ArrayList of some of them, with possible duplicates, as a parameter to some other class's constructor or method and perform operations using them.

Code Description: The code below is a greatly simplified example which is not intended to make much sense from a design perspective. The focus of the problem is the method getResult() within SomeClass and generally how to use an ArrayList of Functions once you have them.

Attempt to solve the problem: The getResult() method implementation is an example of one of many attempts to use the Function list. Again, please don't mind the design of the code. It was just done that way to try to make the problem example as short as possible.

Simple tester class

package com.Testing;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.Function;

public class Tester {

    public static void main(String[] args)
    {
        // Some functions
        Function<Integer, Integer> increment = (Integer input) -> {
            return input + 1;
        };

        Function<Integer, Integer> decrement = (Integer input) -> {
            return input - 1;
        };

        Function<Double, Double> timesPi = (Double input) -> {
            return input * 3.14;
        };

        // list of Functions
        List<Function> availableMathOperations = new ArrayList<>();
        List<Function> selectedMathOperations = new ArrayList<>();

        // populate master list
        availableMathOperations.add(increment);
        availableMathOperations.add(decrement);
        availableMathOperations.add(timesPi);

        // Populate random selection list //
        //    generate random binary number
        Random randomGenerator = new Random();
        int randomNumber = randomGenerator.nextInt(availableMathOperations.size() * 2);
        boolean[] bits = new boolean[availableMathOperations.size()];
        for (int j = 0; j < availableMathOperations.size(); j++) {
            bits[availableMathOperations.size() - 1 - j] = (1 << j & randomNumber) != 0;
        }

        // add math operations to selectedMathOperations based on binary number
        for (int j = 0; j < bits.length; j++) {
            if (bits[j]){
                selectedMathOperations.add(availableMathOperations.get(j));
            }
        }

        SomeClass someClass = new SomeClass(selectedMathOperations, 1.23);

    }
}

Other class

package com.Testing;

import java.util.List;
import java.util.function.Function;

public class SomeClass {

    List<Function> operations;
    double initialValue;

    public SomeClass(List<Function> newOperations, double newInitialValue){
        operations = newOperations;
        initialValue = newInitialValue;
    }

    public double getResult(){
        double result = 0.0;

        // problem method
        // perform the random list of operations using the initial value initially
        for(int i = 0; i < operations.size(); i++){
            if(i == 0)
                result = operations.get(i)(initialValue);
            else
                result += operations.get(i)(result);
        }
        return result;
    }

}

解决方案

The method of a java.util.function.Function object is apply. You need to call it like this:

operations.get(i).apply(initialValue)

However you use raw Function and therefore the result could be Object and you'd need to convert it to the appropriate type. Also you can't use the + (or the +=) operator with it. I'd suggest restricting the parameter types with Number:

List<Function<Number, ? extends Number>> operations = Arrays.asList(
        num ->  num.intValue() + 1,
        num -> num.intValue() - 1,
        num -> num.doubleValue() * 3.14
        ); // just an example list here 

public double getResult() {
    double result = 0.0;

    for (int i = 0; i < operations.size(); i++) {
        if (i == 0) {
            result = operations.get(i).apply(initialValue).doubleValue();
        } else {
            result += operations.get(i).apply(result).doubleValue();
        }
    }
    return result;
}

这篇关于使用Java-8中的函数的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆