Java – remove duplicate code

I'm creating a small function programming library for Java (just to scratch my own itch) When defining high order functions for lists, sets and maps, I encountered this problem: the functions that collect sets and return sets of the same type have almost the same implementation, but must be redefined for each data structure - lists, sets and maps

For example, here is the implementation of map functions for lists and Collections:

public static <A,B> List<B> map(
  List<? extends A> xs,Func1<? super A,? extends B> transformer
) {
  List<B> ys = new ArrayList<B>();
  for(A a : xs) {
    ys.add(transformer.apply(a));
  }
  return ys;
}

public static <A,B> Set<B> map(
  Set<? extends A> xs,? extends B> transformer
) {
  Set<B> ys = new HashSet<B>();
  for(A a : xs) {
    ys.add(transformer.apply(a));
  }
  return ys;
}

Filtering function:

public static <A> List<A> filter(
  List<? extends A> xs,Boolean> predicate
) {
  List<A> ys = new ArrayList<A>();
  for(A a : xs) {
    if(predicate.apply(a)) {
      ys.add(a);
    }
  }
  return ys;
}

public static <A> Set<A> filter(
  Set<? extends A> xs,Boolean> predicate
) {
  Set<A> ys = new HashSet<A>();
  for(A a : xs) {
    if(predicate.apply(a)) {
      ys.add(a);
    }
  }
  return ys;
}

As can be seen from this example, the implementation bodies of set and list are almost the same

There are many functions in my library, such as maps and filters, and each type defines three times the set of each type I am interested in (i.e. list, set and mapping) This leads to a lot of code duplication and code smell I wonder if there are some methods in Java that can help me avoid all code duplication

Any help would be appreciated thank you.

Edit:

Func1 is an interface, which is defined as follows:

interface Func1<A,B> {
  public B apply(A a);
}

Solution

Java does not have high-order polymorphism (also known as higher class), so it is impossible in the type system Many Java programmers resort to XML and / or reflection (i.e. avoiding the type system) to address this deficiency

Scala can handle this. What you describe is called covariant function This fairly basic data type (and more) has been implemented in scalaz libraries, including Java util.* Implementation of

In addition, there are more covariant functions that are not sets and more functions that are not covariant

If you want to explore this particular concept further, you may want Google to "20 intermediate Scala exercises"

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>