functional programming in Java

前端 未结 5 991
滥情空心
滥情空心 2021-01-17 13:58

how can you emulate functional programming in java, specifically, doing things like map a function to a collection of items?

map(func, new String[]{\"a\",\"         


        
5条回答
  •  孤街浪徒
    2021-01-17 14:39

    As you note, Java isn't designed for functional programming and while you can emulate it, you have to really want to do this even if is it more verbose and more awkward than using standard programming in Java.

    Take @Joachim's example.

    Collection result = Collections.transform(input, new Function() {
        public OutputType apply(InputType input) {
          return frobnicate(input);
        }
    });
    

    This uses 12 symbols, not counting close brackets. The same thing in plain Java would look like.

    List list = new ArrayList();
    for(InputType in: input) 
        list.add(frobnicate(in));
    

    This uses 7 symbols.

    You can do functional programming in Java, but you should expect it to be more verbose and awkward than using the natural programming style of Java.

提交回复
热议问题