gpt4 book ai didi

Java - 函数式编程(映射、过滤器)

转载 作者:行者123 更新时间:2023-11-30 05:21:29 26 4
gpt4 key购买 nike

我刚刚开始使用 Java 进行函数式编程。我需要一些简单练习的帮助来加快速度。

假设有以下两个接口(interface):

     interface P {
boolean filter(int v);
}

interface F {
int apply(int v);
}

需要创建一个map函数,该函数将函数f作为参数,并返回一个将f应用于所有节点的节点元素。其次,需要创建一个 filter 函数,该函数返回一个 Node,其中包含与以下类中的谓词 p 匹配的所有元素:

    public class Node {
private int item;
private Node next;

public Node(int item, Node next){
this.item = item;
this.next = next;
}
/* Create a new Node that applies function f to all elements */
public Node map(F f){

}
/* Creates a new Node with all elements that match predicate p */
public Node filter(P p){

}
}

最佳答案

        public Node map(F f){
Node start = new Node(f.apply(item), null);
Node current = start;

for(Node originalNode = this.next; originalNode != null; originalNode = originalNode.next) {

Node copyOfNextNode =new Node(f.apply(originalNode.item), null);
current.next = copyOfNextNode;
current = current.next;
}
return start;
}

/* Creates a new Node with all elements that match predicate p */
public Node filter(P p){
Node start = null;
Node current = null;

for(Node originalNode = this; originalNode != null; originalNode = originalNode.next) {

if(p.filter(originalNode.item)) {
Node copyOfNextNode =new Node(originalNode.item, null);
if(current == null) {
current = copyOfNextNode;
start = current;
} else {
current.next = copyOfNextNode;
current = current.next;
}
}
}
return start;
}

关于Java - 函数式编程(映射、过滤器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59520024/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com