简体   繁体   English

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

[英]Java - Functional Programming (Map, Filter)

I am just getting started with functional programming in Java.我刚刚开始使用 Java 进行函数式编程。 I'd like some help with a simple exercise to get up to speed.我想通过一个简单的练习来帮助你快速上手。

Suppose one has the following two interfaces:假设一个有以下两个接口:

     interface P {
       boolean filter(int v);
     }

     interface F {
      int apply(int v);
    }

and one is required to create a map function that takes a function f as an argument and returns a Node that applies f to all elements.并且需要创建一个map函数,该函数将函数f作为参数并返回一个将f应用于所有元素的节点。 Secondly, one is required to create a filter function that returns a Node with all elements that match a predicate p within the Following class:其次,需要创建一个过滤器函数,该函数返回一个节点,该节点包含与以下类中的谓词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;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM