Kevin's Blog

IT, Java, Ubuntu, Linux

Category: Software Development (page 1 of 6)

Git: Push to / Pull from Both Github and Bitbucket

* Last Updated: 2013-08-26
* Fixed: Bug in the gitpullall() script. – 2013-07-23
* Refactored: gitpullall() – 2013-08-26

Both Github and Bitbucket are good SCM hosting services. For some reason, you probably want to migrate your project from Github to Bitbucket or vice versa. It’s easy because you just need to change the remote repository info. Sometimes, you want to keep your code in both places which means you want to push it to both Github and Bitbucket.

Pushing to both Github and Bitbucket is easy.

Here is a project cloned from Github. If you check out the remote repository info, it has only Github repo info.

The YOUR_PROJECT/.git/config file, of course, has only Github info.

To add a remote git repository on Bitbucket, use git remote set-url.

Now, it has Bitbucket info too.

YOUR_PROJECT/.git/config

Now, run git push -u origin master to set upstream.

It’s enough for pushing to both Github and Bitbucket. So once it’s done, you can just do

Whenever you want to push to both.

e.g.)
Make some changes, Commit and Push

If what you need is only to push to Github and Bitbucket then you don’t need to read this post any further. However, if you also want to pull data from both Github and Bitbucket, it requires a little more extra steps.

Before I show the steps, I need to point out another case that you might want to know. With what I’ve done here, it fetches the data only from Github when running the git pull command. If what you want is only changing it to make it pull from Bitbucket, it’s simple. You just need to swap the positions of origin urls in the YOUR_PROJECT/.git/config file.

So change from this

to

Now it pulls from Bitbucket instead of Github.

To pull from both Github and Bitbucket, first add the remote repository information using git remote.

You can add both Github and Bitbucket or just the one that is not pulled when running git pull. It’s all up to you.
Now, the YOUR_PROJECT/.git/config file contains the information of the new remote repositories just added.

YOUR_PROJECT/.git/config now has “github” and “bitbucket” as well as “origin”.

If you run git pull, it still pulls from only Github so you need to also run git pull bitbucket master.

* pull from Github

or

* pull from Bitbucket

If you want to pull it from all the remote repositories, you can use a function in shell script.

Add the following function to .bash_aliases or .bashrc or .profile depending on your OS (sorry Windows users).

Then you can simply run gitpullall to pull from all the remote repositories specified in the YOUR_PROJECT/.git/config file.

To ignore repositories when pulling, add the remote repository names to the repos_to_ignore variable in the gitpullall function above.

Java Generics: Generics in Real Life Programming

It is surprising to see that there are still many people who do not use generics even when they are using JDK 5 or higher. I can often see it especially when I teach some Java programming subjects at uni. Generics can be very useful and I use it a lot in my libraries and projects. So I’d like to talk about generics but not a basic knowledge of it. I will talk about Java generics in real life programming and how it can be useful as well as some unusual cases may occur and annoy you. I am also going to explain some common cases of generics usage in my next post that I have plan to write soon (hopefully). Then I’m going to write about more complex cases in the sense that it’s complex when it’s designed but rather simple when it’s used, and it’s also more practical. It means I’ll probably write two more posts about generics so stay tuned if you’re interested.

Before I start to talk about usefulness of it, let’s start with problems that can happen if you don’t use generics when using generified types.
If your code looks like this, you’re making your code error-prone.

List list = new ArrayList();

As it discards all the generic type information in the class. To see what exactly happens, better take a look at some example.

If you have type like

public class SomeType<T>
{
  public <E> void test(final Collection<E> collection)
  {
    for (final E object : collection)
    {
      System.out.println("E: " + object);
    }
  }

  public void test(final Set<T> set)
  {
    for (final T t : set)
    {
      System.out.println("T from set: " + t);
    }
  }

  public void test(final List<Integer> integerList)
  {
    int result = 0;
    for (final Integer integer : integerList)
    {
      result += integer.intValue();
    }
    System.out.println("result: " + result);
  }
}

and execute code like

final SomeType someType = new SomeType();
final List<String> list = Arrays.asList("some", "test", "value");
someType.test(list);

Then you will get ClassCastException saying “java.lang.String cannot be cast to java.lang.Integer” in runtime but no errors in compile-time. Why? because it uses public void test(final List<Integer> integerList) method instead of public <E> void test(final Collection<E> collection). But why does it use the one taking List of Integer instead of the one with the Collection of some type E when the passed parameter is a List of String which is a Collection of some type E, in this case, String? The reason is that SomeType is generified but when using it, no generics are used. If generified type is used without generic type info specified, the Java compiler makes it like the old type in JDK prior to 5.0 which doesn’t have generics.

Thus, the methods above all become like

  public void test(final Collection collection)

  public void test(final Set set)

  public void test(final List integerList)

So the closest type matched with a List of String is a List and that’s why public void test(final List<Integer> integerList) is called. But the method, public <E> void test(final Collection<E> collection), has nothing to do with the generic type specified in the class SomeType<T>. It’s just a generic method and the E has nothing to do with the T. Yeah, but if the type is generified, yet no generic type is specified when it is used, all the generics info including the ones in the generic methods is gone.

To solve the problem, you just need to specify the generic type. In the case above, you can even use just ‘?‘ (wildcard) since you’re not using the generic type specified in the class but the generic method, public <E> void test(final Collection<E> collection).

final SomeType<?> someType = new SomeType<Object>();
final List<String> list = Arrays.asList("some", "test", "value");
someType.test(list);

Now, with generics, you don’t have the problem you had before without generics.

So, it’s clear why you should use generics when using generified types. What I just explained is actually not new but well known to most Java programmers. Now, let’s talk about some benefits from using generics.

You can avoid a problem that you have with arrays if you use generics. Arrays of reference types in Java are covariant so you may have a problem like this.

  final Integer[] integerArray = { 1, 2, 3, 4, 5 };
  final Object[] objectArray = integerArray;
  objectArray[0] = "test";

There is no compile-time error, yet running this code results in java.lang.ArrayStoreException: java.lang.String when objectArray[0] = "test"; is executed.

Unlike arrays, generics are invariant, so if you use generics like,

  final List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
  final List<Object> objectList = integerList;

You get a compile-time error.

  final List<Object> objectList = (List<Integer>) integerList; // compile-time error

Even this one causes the compile-time error too since a List of Integer is not a subtype of List of Object (In arrays, an Integer array is a subtype of Object array).

On the other hand, you may need to cast it although it happens very occasionally. Here is an example taken from one of my libraries.
In KommonLee ASM, there is a visitor class, MethodAnalysisClassVisitor.

public class MethodAnalysisClassVisitor<T, M extends Member> extends EmptyVisitor
{
  private final MemberCollector<M> memberCollector;
  private final Class<T> theClass;
  private final Map<M, String[]> memberToParameterNamesMap;

  public MethodAnalysisClassVisitor(final MemberCollector<M> memberCollector, final Class<T> theClass,
      final Map<M, String[]> memberToParameterNamesMap)
  {
    this.memberCollector = memberCollector;
    this.theClass = theClass;
    this.memberToParameterNamesMap = memberToParameterNamesMap;
  }
  // Remainder omitted...
}

This visitor collects all the methods / constructors and their parameter names. Why do I need this kind of tool? It’s because I needed to get the parameter names of constructors in a class for one of my libraries, JSON Statham, but there was no easy way to get the parameter names of methods or constructors in Java. Reflection in Java certainly doesn’t have this convenience which is, I believe, an integral part for library / framework development although it would be depending on what sort of library it is. So I had to use ASM to get the method parameter names. I was shocked when I first discovered it. Anyway, back to the original topic again, the visitor is used by AsmMethodAndConstructorAnalyser.

public class AsmMethodAndConstructorAnalyser implements MethodAndConstructorAnalyser
{
  // ...

  @Override
  public <T> Map<Constructor<T>, String[]> findConstructorsWithParameterNames(final Class<T> theClass)
      throws IllegalArgumentException
  {
    final Map<Constructor<T>, String[]> constructorToParameterNamesMap = new LinkedHashMap<Constructor<T>, String[]>();

    @SuppressWarnings({ "cast", "unchecked", "rawtypes" })
    final Map<Constructor<?>, String[]> map = (Map<Constructor<?>, String[]>) ((Map) constructorToParameterNamesMap);

    getClassReader(theClass).accept(
        new MethodAnalysisClassVisitor<T, Constructor<?>>(constructorCollector, theClass, map), 0);
    return constructorToParameterNamesMap;
  }
  // ...
}

I know that the type M defined in the MethodAnalysisClassVisitor is Constructor<T> in this particular method as I’m passing Class<T> and want to collect all the constructors in it which are all Constructor<T>, yet the Java compiler can’t figure it out so I get a compile-time error if I just do

    final Map<Constructor<T>, String[]> constructorToParameterNamesMap = new LinkedHashMap<Constructor<T>, String[]>();

    getClassReader(theClass).accept(
        new MethodAnalysisClassVisitor<T, Constructor<?>>(constructorCollector, theClass, constructorToParameterNamesMap), 0);

Therefore, what I did was:
first, cast Map<Constructor<T>, String[]> constructorToParameterNamesMap to a raw type Map then it will lose all the generic type info.
second, I can cast it to Map of any key value pair since the Java compiler erases all the generic types when it’s compiled.
finally, I ended up having the following lines of code. I had to add @SuppressWarnings({ "cast", "unchecked", "rawtypes" }) to make the compiler happy. I could do it because I know the constructors stored in the Map are all Constructors of T type.

  @SuppressWarnings({ "cast", "unchecked", "rawtypes" })
  final Map<Constructor<?>, String[]> map = (Map<Constructor<?>, String[]>) ((Map) constructorToParameterNamesMap);

  getClassReader(theClass).accept(
      new MethodAnalysisClassVisitor<T, Constructor<?>>(constructorCollector, theClass, map), 0);

This doesn’t happen often though. So most of the time, you don’t need to do it and can enjoy type safety that generics offer.

Along with the benefit I mentioned above with the case compared with arrays, generics offer convenience of postponing specifying the type information until it is used with compile-time type safety. One example that everyone knows is Java’s collections framework. The programmer of collections didn’t know what types would be stored in the collections when it was created, thus when it came out, it stored just an object type as there were no generics. This is the part where Java loses static typing although it’s a static type language. However, after introduction of generics, the users of collections can have compile-time type safety. Ironically, the collections are one of the most popular examples of how generics can be useful, yet according to Neal Gafter, it’s one of the most important reasons why generics are implemented using type erasure and wild-card, which make generics more complex. If you’re interested in it, you’d better watch his presentation.

Although Generics were introduced in JDK 5.0, the GJ compiler that can handle generics were introduced much earlier in JDK 1.3 but it was disabled according to the Java language specification.

Generics give us compile-time type safety but it’s compile-time only because, as I just mentioned, it does type erasure which means the compiler removes all the generic type information when it compiles, and that’s why we can’t create a generic type object or array like.

T t = new T();
T[] t = new T[10];

This is impossible in Java and that’s why you don’t see method like E[] toArray() but Object[] toArray() and <T> T[] toArray(T[] a) in the Collection class and its sub classes. You can create an array of E type if an instance of array of E is given as a parameter value. For example,

public <E> E[] copyArray(final E[] array)
{
  @SuppressWarnings("unchecked")
  final E[] copiedArray = (E[]) Array
                          .newInstance(array
                                        .getClass()
                                        .getComponentType(),
                                      array.length);
  System.arraycopy(array, 0, copiedArray, 0, array.length);
  return copiedArray;
}

It takes an array of E object then creates a new array object of E then copies all the elements in the given one to the new one then returns it.

How is it possible? It’s possible because now I’m dealing with an ‘array object’ of E type not the generic type E directly so I can get the class of the array object in order to take the component type of the element stored in the array. So first, get the class of E[] ‘object’ (not class) which is a parameter value and given in runtime, then I can get the component type of it. However, the following case is impossible.

public <E, NE, F extends Function1<E, NE>> NE[] apply(final F function, final E[] source)
{
  final List<NE> list = new ArrayList<NE>();
  for (final E element : source)
  {
    list.add(function.apply(element));
  }
  @SuppressWarnings("unchecked")
  final NE[] resultArray = list.toArray(
      (NE[]) Array
          .newInstance(NE[].class // <- compile time error here: Illegal class literal for the type parameter NE!!!
                      .getComponentType(),
                       list.size()));
  return resultArray;
}

Because there is no such thing as an NE[] ‘class’ (not object), there is no way to get the class. When it’s compiled, NE[] becomes an Object array (Object[]).

I used to hate this type erasure as I had some issues when I developed my libraries. However, I do not anymore. It’s not just because of the reason mentioned here. I have mine and will explain it later in this post.

So let me talk about why we use generics again. We use it to have compile-time type safety without having to decide the type when designing the API. One example can be found in my old post about Easier and Better Way to Use JDBC. Simply, it makes use of callback function object much more useful.

Let’s say you want to map a type stored in a List to some other type. If you don’t use generics, you probably need to make a method for each mapped type like

public List<BigDecimal> takePricesOf(List<Product> list)
{
  List<BigDecimal> newList = new ArrayList<BigDecimal>();
  for (Product product : list)
  {
    newList.add(product.getPrice());
  }
  return newList;
}

public List<DiscountedProduct> toDiscountedProducts(int discountRate, List<Product> list)
{
  List<DiscountedProduct> newList = new ArrayList<DiscountedProduct>();
  for (Product product : list)
  {
    newList.add(new DiscountedProduct(product, discountRate));
  }
  return newList;
}

// and more...

(OK, here are actually generics used but it’s only for using List).

It can become one reusable method with some callback function object like.

public interface Mapper
{
  Object map(Object input);
}
public List<Object> mapWithoutGenerics(Mapper mapperWithoutGenerics, List<?> list) // <- this cannot be List<Object> since you want to pass a List of any type not just List<Object>.
{
  List<Object> newList = new ArrayList<Object>();
  for (Object object : list)
  {
    newList.add(mapperWithoutGenerics.map(object));
  }
  return newList;
}

When you use it.

List<Object> productPriceList = mapWithoutGenerics(new Mapper() {
  public Object map(Object input)
  {
    Product product = (Product) input;
    return product.getPrice();
  }
}, productList);

Now, you don’t have compile-time type safety anymore so you may pass a List of any type.
So the following code doesn’t cause any compile-time error but the runtime exception that is java.lang.ClassCastException.

List<Object> productPriceList = mapWithoutGenerics(new Mapper() {
  public Object map(Object input)
  {
    Product product = (Product) input;
    return product.getPrice();
  }
}, Arrays.asList("Some", "String", "List"));

 

It can surely become much better with generics.

public interface Function1<T, R>
{
  R apply(T input);
}
public <T, R, F extends Function1<T, R>> List<R> map(F mapper, List<T> list)
{
  final List<R> newList = new ArrayList<R>();
  for (final T t : list)
  {
    newList.add(mapper.apply(t));
  }
  return newList;
}

Then when you use it.

final List<BigDecimal> productPriceList = map(new Function1<Product, BigDecimal>() {
  @Override
  public BigDecimal apply(final Product product)
  {
    return product.getPrice();
  }
}, productList);

Or the function object can be reused.

private static final Function1<Product, BigDecimal> PRODUCT_TO_PRICE_MAPPER = new Function1<Product, BigDecimal>() {
  @Override
  public BigDecimal apply(final Product product)
  {
    return product.getPrice();
  }
};

//...

final List<BigDecimal> productPriceList        = map(PRODUCT_TO_PRICE_MAPPER, productList);
final List<BigDecimal> anotherProductPriceList = map(PRODUCT_TO_PRICE_MAPPER, anotherProductList);

The other method that is toDiscountedProducts() can be done with this generic map method and closure.

final int discountRate = 15;

final List<DiscountedProduct> discountedProductList = map(new Function1<Product, DiscountedProduct>() {
  @Override
  public DiscountedProduct apply(final Product product)
  {
    return new DiscountedProduct(product, discountRate);
  }
}, productList);
Although Java doesn’t really have closure, the Function1 above is used as a closure because it’s accessing a non-local variable, and in almost all the cases when people say that Java doesn’t have closure, they actually mean a way to support first-class functions (e.g. lambda expression to support first-class functions in Java).

Speaking of generics used for collections, I should point out that it would have been much more useful, if the collections had got methods like select (or filter), map, etc.

So if you had got a List of Integer and wanted to get all the positive ones, you would have done like.

List<Integer> positiveIntegerList = integerList.select(new Condition1<Integer>() {
  public boolean isMet(Integer integer)
  {
    return 0 < integer.intValue();
  }
});

Or getting all the prices from the List of Product object as I already showed. Unfortunately Java’s Collections don’t have those methods. Well, my collection library has it, but it’s incomplete and not so compatible with existing code using Java’s collections although it has a way to convert from and to Java ones. So to keep using Java’s collections, I made some helper methods to achieve the goal which is having one generic method to apply different kinds of functions to all the elements in the collections. By the way, why do I bother about it? Can’t I just use for or foreach loop? Sure, I can. So why? With the generic methods mentioned above and function objects, I can focus on the actual problems. For instance, to get all the prices from the list of Product, my concern should be getting the price of each Product not how to use for or foreach loop.

Here, I need to worry about using foreach and creating ArrayList.

List<BigDecimal> productPriceList = new ArrayList<BigDecimal>();
for (Product product : productList)
{
  productPriceList.add(product.getPrice());
}

With the generic one (if there were one), I wouldn’t.

List<BigDecimal> productPriceList = productList.map(new Function1<Product, BigDecimal>() {
  public BigDecimal apply(Product product)
  {
    return product.getPrice(); // <- here I'm focusing on getting the price.
  }
});

Since Java doesn’t support first-class function, the syntax is not so pleasant. However, JDK 8 will have lambda expression to support it so when it comes out, it can probably be like.

List<BigDecimal> productPriceList = productList.map((product) -> product.getPrice());
// It hasn't been finalised yet so the syntax can be different.

Anyway, Java collections still don’t have those methods so, as I said already, I made the ones for the collections. So let me talk about one of these that is Selector. What Selector does is checking all the elements in a collection and takes only the ones that meet the given Condition. I wanted to have only one Selector that can easily deal with all the classes extends Collection instead of having one for each (e.g. ListToArrayListSelector, ListToHashSetSetSelector, SetToListSelector, and so on). Thus I made it like this.

public class IterableToCollectionSelector<E, T extends Iterable<? extends E>, C extends Condition1<? super E>, R extends Collection<E>>
    implements Selector1<T, C, R>
{
  @Override
  public R select(final C condition, final T source)
  {
    final R result = // <- How can I get the Collection instance of R?
    for (final E element : source)
    {
      if (condition.isMet(element))
      {
        result.add(element);
      }
    }
    return result;
  }
}

Here are Condition1 and Selector1 in my library.

public interface Condition1<T>
{
  boolean isMet(T input);
}
public interface Selector1<T, C, R>
{
  R select(C condition, T source);
}

Let me explain it step by step. First,

public class IterableToCollectionSelector<E, T extends Iterable<? extends E>, C extends Condition1<? super E>, R extends Collection<E>>
    implements Selector1<T, C, R>
E
E is a type of an element stored in the given collection.
T

T is any type extends Iterable of the type extends E.

  1. Why is it Iterable of any type extends E (? extneds E)? Otherwise, you can’t use a List of any sub type of E.
    It would be easier to understand with an example. Let’s say you need to get a List of Product the price of which is greater than 50 dollars. If it’s just Iterable<E> then you have no problem with passing a List of Product yet you do have when you try to pass a List of DiscountedProduct which is a sub class of Product and it should be perfectly valid to pass it as a parameter of the selector made for Product (Think about Liskov substitution principle).
    If you have Iterable<? extends E>, you can pass E type and any sub-types of E, in this case, Product and DiscountedProduct are all fine.
  2. Then why T extends Iterable? Can I just have Iterable for the input type then I can remove the generic type T? Yes, it’s OK, but what if there is anyone who wants to extends this class and wants to restrict the input type to only List instead of any sub-type of Iterable (probably if you care about Open/closed principle)?
    If you have a class like this.

    // Notice that T extends Iterable<? extends E> is gone, and it has Iterable<? extends E> instead (No T).
    public class IterableToCollectionSelector<E, C extends Condition1<? super E>, R extends Collection<E>> implements
      Selector1<Iterable<? extends E>, C, R>
    {
    }
    

    You can’t restrict the input type to something other than Iterable<? extends E>, and if you try to override the select method in the sub-class of it.
    e.g.)

    public class IterableToArrayListSelector<E> extends
      IterableToCollectionSelector<E, Condition1<? super E>, ArrayList<E>>
    {
      @Override
      public ArrayList<E> select(final Condition1<? super E> condition, final List<? extends E> source)
      {
        return super.select(condition, source);
      }
    }
    

    You will get a compile-time error because T is not the same as “? extends T“. In this case, “Iterable<? extends E>” specified as a generic type T for the Selector1<T, C, R> is not the same as “? extends T” that is, in here, List<? extends E> (one of “T extends Iterable<? extends E>“) in the overridden method select() (It’s not actually overridden as List<? extends E> can’t be a substitute for Iterable<? extends E> here). Still not sure why List can’t be used? Well, think about this. List<String> is not the same as and can’t be a substitute for List<Object>. You know it, and I already explained it earlier when I talked about the side-effect of using arrays. Then think about this one. Can List<List<?>> be a substitute for List<Iterable<?>>? No, it’s just like List<String> and List<Object>, and the problem we have here is the same.

    So

    public class IterableToCollectionSelector<E, T extends Iterable<? extends E>, C extends Condition1<? super E>, R extends Collection<E>>
      implements Selector1<T, C, R>
    

    gives me freedom to restrict the input iterable to whatever extends Iterable I want.
    e.g.)

    public class IterableToArrayListSelector<E> extends
        IterableToCollectionSelector<E, List<? extends E>, Condition1<? super E>, ArrayList<E>>
    

    There will be a compile-time error when passing a Set instead of a List for the input value of the select() method.

C extends Condition1<? super E>
Next one is C extends Condition1<? super E>. What? Why is the input type of the Condition1? super E“? Because, with “? super E“, I can have one Condition1 object for many sub-types of the type E. Imagine that you want to get a List of Product the price of which is greater than 20, you can have a Condition1 for Product, then if you also need to get a List of DiscountedProduct the price of which is also greater than 20, you can reuse that Condition1 object for it as DiscountedProduct is a sub-type of Product which means Condition1<Product> is a kind of Condition1<? super DiscountedProduct>. If I have “C extends Condition1<E>” then I can’t do that, but because it’s “C extends Condition1<? super E>“, I can.
R
The last one is R. R extends Collection<E> so it can be any sub-type of Collection.

Now let’s look at the method. Here I have some problem.

  public R select(final C condition, final T source)
  {
    final R result = // <- How can I get the Collection instance of R???
    for (final E element : source)
    {
      if (condition.isMet(element))
      {
        result.add(element);
      }
    }
    return result;
  }

If it’s one type of Collection, I can easily create it but it’s not determined yet. It will be set when it’s used. Then why don’t I postpone instantiation of it until it’s used. More precisely when the selector is instantiated. So I just create another type to create one of Collection also using generics.

public interface CollectionCreator<E, T extends Collection<? extends E>>
{
  T createCollection();
}

So it can be used to create any sub-types of Collection.
e.g.) for ArrayList

public class ArrayListCreator<E> implements CollectionCreator<E, ArrayList<E>>
{
  @Override
  public ArrayList<E> createCollection()
  {
    return new ArrayList<E>();
  }
}

for HashSet

public class HashSetCreator<E> implements CollectionCreator<E, HashSet<E>>
{
  @Override
  public HashSet<E> createCollection()
  {
    return new HashSet<E>();
  }
}

With all these, the final version of IterableToCollectionSelector is

public class IterableToCollectionSelector<E, T extends Iterable<? extends E>, C extends Condition1<? super E>, R extends Collection<E>>
    implements Selector1<T, C, R>
{
  private final CollectionCreator<E, ? extends R> collectionCreator;

  public <CC extends CollectionCreator<E, ? extends R>> IterableToCollectionSelector(final CC collectionCreator)
  {
    this.collectionCreator = collectionCreator;
  }

  @Override
  public R select(final C condition, final T source)
  {
    final R result = collectionCreator.createCollection();
    for (final E element : source)
    {
      if (condition.isMet(element))
      {
        result.add(element);
      }
    }
    return result;
  }
}

It needs to have CollectionCreator but it’s immutable so I don’t need to worry about the state of the selector object once it’s created.

When IterableToCollectionSelector is used, it looks

// selector for the List of Product.
final IterableToCollectionSelector<Product, Iterable<Product>, Condition1<Product>, ArrayList<Product>> collectionSelector =
  new IterableToCollectionSelector<Product, Iterable<Product>, Condition1<Product>, ArrayList<Product>>(new ArrayListCreator());
final List<Product> resultList = collectionSelector.select(greaterThan20, productList);

// selector for the List of DiscountedProduct
final IterableToCollectionSelector<DiscountedProduct, Iterable<DiscountedProduct>, Condition1<Product>, ArrayList<DiscountedProduct>> collectionSelector2 =
  new IterableToCollectionSelector<DiscountedProduct, Iterable<DiscountedProduct>, Condition1<Product>, ArrayList<DiscountedProduct>>(new ArrayListCreator());
final List<DiscountedProduct> resultList2 = collectionSelector2.select(greaterThan20, discountedProductList)

Wait, do I have to create the IterableToCollectionSelector whenever I need to use it for a different type? It seems like it’s waste of memory and not to mention of boilerplate code. OK, here comes why I don’t hate generics’ type erasure anymore. Considering type erasure, both objects, used above, actually have no difference in runtime.

So what I can do is that I can create a helper class containing one really generic IterableToCollectionSelector then cast it using a generic method so that it always returns the same instance but can be used for different types with compile-time type safety. It would be clear if I just show the code.

public class CollectionUtil
{
  private static final IterableToCollectionSelector<?, ? extends Iterable<?>, ? extends Condition1<?>, ? extends ArrayList<?>> ITERABLE_TO_ARRAY_LIST_SELECTOR =
    new IterableToCollectionSelector<Object, Iterable<?>, Condition1<Object>, ArrayList<Object>>(
        new ArrayListCreator<Object>());

  public static <E, T extends Iterable<? extends E>, C extends Condition1<? super E>> IterableToCollectionSelector getIterableToCollectionSelector()
  {
    @SuppressWarnings("unchecked")
    final IterableToCollectionSelector<E, T, C, ArrayList<E>> iterableToCollectionSelector =
      (IterableToCollectionSelector<E, T, C, ArrayList<E>>) ITERABLE_TO_ARRAY_LIST_SELECTOR;
    return iterableToCollectionSelector;
  }
}

And similarly, ArrayListCreator doesn’t have to be created more than once. It doesn’t have any state so one instance can be and should be reused.

public class ArrayListCreator<E> implements CollectionCreator<E, ArrayList<E>>
{
  public static final ArrayListCreator<Object> ARRAY_LIST_CREATOR = new ArrayListCreator<Object>();

  @Override
  public ArrayList<E> createCollection()
  {
    return newArrayList();
  }

  public static <E> ArrayListCreator<E> getInstance()
  {
    @SuppressWarnings("unchecked")
    final ArrayListCreator<E> arrayListCreator = (ArrayListCreator<E>) ARRAY_LIST_CREATOR;
    return arrayListCreator;
  }
}

So CollectionUtil is rewritten.

public class CollectionUtil
{
  private static final IterableToCollectionSelector<?, ? extends Iterable<?>, ? extends Condition1<?>, ? extends ArrayList<?>> ITERABLE_TO_ARRAY_LIST_SELECTOR =
    new IterableToCollectionSelector<Object, Iterable<?>, Condition1<Object>, ArrayList<Object>>(
        ArrayListCreator.getInstance());

  public static <E, T extends Iterable<? extends E>, C extends Condition1<? super E>> IterableToCollectionSelector getIterableToCollectionSelector()
  {
    @SuppressWarnings("unchecked")
    final IterableToCollectionSelector<E, T, C, ArrayList<E>> iterableToCollectionSelector =
      (IterableToCollectionSelector<E, T, C, ArrayList<E>>) ITERABLE_TO_ARRAY_LIST_SELECTOR;
    return iterableToCollectionSelector;
  }
}
@SuppressWarnings("unchecked")
final IterableToCollectionSelector<E, T, C, ArrayList<E>> iterableToCollectionSelector =
  (IterableToCollectionSelector<E, T, C, ArrayList<E>>) ITERABLE_TO_ARRAY_LIST_SELECTOR;

This is possible due to type erasure, so you don’t have to create many objects of the same type with different generic type info (e.g. instances of the same type, ‘IterableToCollectionSelector‘, with ‘different generic types’ like different E, T, C) which will be all the same in runtime. That’s why I do not hate type erasure anymore. Of course, you need to @SuppressWarnings to make the compiler quiet, but it’s not a big deal and I know what I’m doing. It’s perfectly valid.

The condition can be reused.

final Condition1<Product> greaterThan20 = new Condition1<Product>() {
  private final BigDecimal twenty = new BigDecimal("20");
  @Override
  public boolean isMet(final Product input)
  {
    return 0 > twenty.compareTo(input.getPrice());
  }
};

Now I can just do,

final IterableToCollectionSelector<Product, Iterable<Product>, Condition1<Product>, ArrayList<Product>> collectionSelectorForProduct =
  CollectionUtil.getIterableToCollectionSelector();
final List<Product> resultForProduct = collectionSelectorForProduct.select(greaterThan20, productList);

final IterableToCollectionSelector<DiscountedProduct, Iterable<DiscountedProduct>, Condition1<Product>, ArrayList<DiscountedProduct>> collectionSelectorForDiscountedProduct =
  CollectionUtil.getIterableToCollectionSelector();
final List<DiscountedProduct> resultForDiscountedProduct = collectionSelectorForDiscountedProduct.select(greaterThan20, discountedProductList);

Each time when you get an instance of IterableToCollectionSelector using the getIterableToCollectionSelector() method, you get the same IterableToCollectionSelector instance.

OK, that sounds good but do I really need to know all those complex E, T, C, R and even wildcard like “? extends E” or “? super E“? Well, you don’t have to. It depends on what you do. If you’re a library or framework developer, you should probably. Otherwise, not really. The library or API designer should carefully design it to offer APIs that are easy to use and understand for the users of the library. The designer or architect, on the other hand, should know the things I talked about here to make complex things simple. That’s our job, isn’t it? Making a complex thing simple then solve it. Anyway, most of the time, you don’t need to deal with that kind of complex API if you’re an application developer. Your company should have at least one person who can deal with it and he/she should provide easy to use APIs. If your company doesn’t have any, ask your boss to hire one. :) Using well designed good APIs can surely save your time which means saving your company’s money. Also less error-prone.

So how can the IterableToCollectionSelector be simple so that the users wouldn’t need to care about E, T, C, etc.

The library designer should create more specific type of selector like

public final class IterableToArrayListSelector<E> extends
    IterableToCollectionSelector<E, Iterable<? extends E>, Condition1<? super E>, ArrayList<E>>
{
  IterableToArrayListSelector(final ArrayListCreator<E> collectionCreator)
  {
    super(collectionCreator);
  }
}

Then CollectionUtil becomes

public class CollectionUtil
{
  private static final IterableToArrayListSelector<?> ITERABLE_TO_ARRAY_LIST_SELECTOR =
    new IterableToArrayListSelector<Object>(ArrayListCreator.getInstance());

  public static <E> IterableToArrayListSelector<E> getIterableToArrayListSelector()
  {
    @SuppressWarnings("unchecked")
    final IterableToArrayListSelector<E> iterableToCollectionSelector =
      (IterableToArrayListSelector<E>) ITERABLE_TO_ARRAY_LIST_SELECTOR;
    return iterableToCollectionSelector;
  }
}

Now using it is much easier.
(with static import)

import static your.package_name.here.CollectionUtil.*;

// ...

final IterableToArrayListSelector<Product> arrayListSelectorForProduct =
  getIterableToArrayListSelector();
final List<Product> resultForProduct = arrayListSelectorForProduct.select(greaterThan20, productList);

final IterableToArrayListSelector<DiscountedProduct> arrayListSelectorForDiscountedProduct =
  getIterableToArrayListSelector();
final List<DiscountedProduct> resultForDiscountedProduct =
  arrayListSelectorForDiscountedProduct.select(greaterThan20, discountedProductList);

You may not be satisfied yet, because you have the variables for the IterableToArrayListSelector objects. Should you have these? No, you don’t have to. So you probably try like this.

final List<Product> resultForProduct = getIterableToArrayListSelector()
                                         .select(greaterThan20, productList);

Yet, this doesn’t work. When getIterableToArrayListSelector() is called there is no generic type info given so it returns just an object of IterableToArrayListSelector<Object>. Thus it causes a compile-time error on calling select(greaterThan20, productList).

It can be solved by specifying the generic type like.

final List<Product> resultForProduct2 = CollectionUtil.<Product> getIterableToArrayListSelector()
                                          .select(greaterThan20, productList);

It’s not so elegant though. It can be solved as well. How? instead of having the getIterableToArrayListSelector() method to get an instance of IterableToArrayListSelector, why don’t I just create another generic select() method which does both getting the instance and calling the select() method in it.

So CollectionUtil is re-written.

public class CollectionUtil
{
  private static final IterableToArrayListSelector<?> ITERABLE_TO_ARRAY_LIST_SELECTOR =
    new IterableToArrayListSelector<Object>(ArrayListCreator.getInstance());

  public static <E, T extends Iterable<? extends E>, C extends Condition1<? super E>> ArrayList<E> select(
      final C condition, final T iterable)
  {
    final IterableToArrayListSelector<E> iterableToCollectionSelector =
      (IterableToArrayListSelector<E>) ITERABLE_TO_ARRAY_LIST_SELECTOR;
    return iterableToCollectionSelector.select(condition, iterable);
  }
}

How to use? Really simple.
(also with static import)

import static your.package_name.here.CollectionUtil.*;

// ...

final List<Product> resultForProduct = select(greaterThan20, productList);

final List<DiscountedProduct> resultForDiscountedProduct = select(greaterThan20, discountedProduct);

So it’s

final IterableToCollectionSelector<Product, Iterable<Product>, Condition1<Product>, ArrayList<Product>> collectionSelectorForProduct =
  getIterableToCollectionSelector();
final List<Product> resultForProduct = collectionSelectorForProduct.select(greaterThan20, productList);

VS

final List<Product> resultForProduct = select(greaterThan20, productList);

As you can see, depending on how you use generics it can give you a really nice, simple and easy to use API.

Just a moment. It might not be enough. That select takes an Iterable object and returns an ArrayList object, but what if I want to get HashSet instead, or what about taking an array as an input parameter instead of an Iterable object? It can be accomplished too, but I’m not going to explain it here. I’ll do it later when I talk about good API design in another post not in the generics series.

In the meantime, you can use what I’ve already provided in my library that is KommonLee.

If you use it, you can simply do

final List<Product> anotherPositiveIntegerList = selector()
        .fromIterable()
        .toArrayList()
        .select(greaterThan20, productList);

OR

final Set<Product> anotherPositiveIntegerList = selector()
        .fromIterable()
        .toHashSet()
        .select(greaterThan20, productList);

OR

Product[] productArray = // ...
final List<Product> anotherPositiveIntegerList = selector()
        .fromArray()
        .toArrayList()
        .select(greaterThan20, productArray);

and so on…
More examples are >>here<<
It also has Mappers and SelectableMappers so you can convert one type stored in a Collection to another.

Also the example code I used here is available on Github. Example Code: CLICK HERE!!!

Next post about generics would be about something easier than the selector example. So it would be some practical but easier, then the final post would be about really complex one when it’s designed but easy when it’s used. It is also very practical and useful. Unfortunately, however, I can’t tell when I can write it as I need to think about good examples to explain. As you can see above, it can be difficult to understand without example code (or even with it, still difficult). I do actually have some examples but it’s the code I made for my work so I can’t just use it. Anyway, I will figure it out so stay tuned.
 
 

Thanks for those who retweeted and favorited this post.

 

New Homepage

I’ve renovated my homepage.

The old one was

My homepage – OLD

The new one is

My homepage – New


It looks much better in Google Chrome and Firefox than IEs (It doesn’t work in IE6 at all).

My projects and about me page are also added.

My Projects

About Me

Videos I recommend to (Java) Programmers

For better Java programming

Google I/O 2008 – Effective Java Reloaded – Joshua Bloch


 
 

Effective Java – Still Effective After All These Years – Joshua Bloch


 
 
 
 

For better API / language design

Growing a Language, by Guy Steele


 
 

How To Design A Good API and Why it Matters – Joshua Bloch


 
 

Evolving the Java Language – Neal Gafter

http://www.infoq.com/presentations/neal-gafter-evolving-java
 
 

Advanced Topics In Programming Languages: Closures For Java – Neal Gafter

Look and Say Sequence (Java)

Look and say sequence is the sequence of numbers generated from the previous number by reading off the digits of which the number consists.

So the first number is 1 then there is one "1". one 1 -> 11
Now use the number "11" and there are two 1s. two 1s -> 21
21: one 2 and one 1 -> 1211
1211: one 1, one 2 and two 1s -> 111221
111221: three 1s, two 2s and one 1 -> 312211
312211: one 3, one 1, two 2s and two 1 -> 13112221
13112221: one 1, one 3, two 1s, three 2s and one 1 -> 1113213211
----------------------------------------------------------------
1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211 ...

The Java programme code which reads off the given number can be written like

public static String LookAndSayUsingForLoop(final String number)
{
  if (null == number || number.isEmpty())
  {
    return "";
  }
  int firstCharPosition = 0;
  final StringBuilder stringBuilder = new StringBuilder();
  for (int i = 0; i < number.length(); i++)
  {
    if (number.charAt(firstCharPosition) != number.charAt(i))
    {
      //
      // the char at the current position is not equal to the first char
      // in the group of the equal chars so collect the chars
      // from the first char position to just before the current position.
      //
      final String digitsFound = number.substring(firstCharPosition, i);
      stringBuilder.append(digitsFound
                          .length())
                   .append(number
                          .charAt(firstCharPosition));
      firstCharPosition = i; // set the new first char position
    }
  }
  /* add the leftover */
  stringBuilder.append(number
                      .substring(firstCharPosition,
                                 number.length())
                      .length())
               .append(number
                      .charAt(firstCharPosition));
  return stringBuilder.toString();
}
System.out.println(LookAndSayUsingForLoop("1"));
Result:
11
System.out.println(LookAndSayUsingForLoop("11"));
Result:
21
System.out.println(LookAndSayUsingForLoop("21"));
Result:
1211

So to get the first ten elements,

String result1 = number;
System.out.print(result1 + " ");
for (int i = 1; i < howMany; i++)
{
  result1 = LookAndSayUsingForLoop(result1);
  System.out.print(result1 + " ");
}

It prints out.

1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 

It can be simpler if recursion is used.
The LookAndSayUsingForLoop method can be re-written like

private static String lookAndSayV1(final String number, final int position)
{
  if (number.length() == position)
  {
    // reached the end which means every digit in the number is
    // equal to one another so just read off the entire number.
    return String.valueOf(number.length()) + number.charAt(0);
  }
  final char firstChar = number.charAt(0);
  return firstChar == number.charAt(position) ?
            // the current char equals to the first one so keep checking
            lookAndSayV1(number, position + 1) :
            // otherwise, read off until just before the current position
            // then check from the current position
            // calling this function itself again.
            String.valueOf(number
                          .substring(0, position)
                          .length()) +
              firstChar +
              lookAndSayV1(number
                          .substring(position), 0);
}

The result is exactly the same as the one using ‘for’ loop.

System.out.println(lookAndSayV1("1", 0));
Result:
11
System.out.println(lookAndSayV1("11", 0));
Result:
21
System.out.println(lookAndSayV1("21", 0));
Result:
1211

To get the first ten elements, another recursive method can be used.

public static String lookAndSay(final int howMany, final String number)
{
  return 0 >= howMany ? "" : number + " " + lookAndSay(howMany - 1, lookAndSayV1(number, 0));
}
final String number = "1";
final String result = lookAndSay(10, number);
System.out.println(result);

Result:

1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 

The method lookAndSayV1() can be re-written using only one return statement and a few conditional operations.

private static String lookAndSayV2(final String number, final int position)
{
  return number.length() == position ?
            String.valueOf(number
                          .length()) +
              number.charAt(0) :
            (number.charAt(0) == number.charAt(position) ?
                lookAndSayV2(number, position + 1) :
                String.valueOf(number
                              .substring(0, position)
                              .length()) +
                  number.charAt(0) +
                  lookAndSayV2(number
                            .substring(position), 0));
}

This works the same as the lookAndSayV1() method. The code would be more readable with readOff() method.

private static String readOff(final String digits)
{
  return String.valueOf(digits.length()) + digits.charAt(0);
}

private static String lookAndSayV3(final String number, final int position)
{
  return number.length() == position ?
            readOff(number) :
            (number.charAt(0) == number.charAt(position) ?
                lookAndSayV3(number, position + 1) :
                readOff(number
                      .substring(0, position)) +
                      lookAndSayV3(number
                                  .substring(position), 0));
}

public static String lookAndSay3(final int howMany, final String number)
{
  return 0 >= howMany ? "" : number + " " + lookAndSay3(howMany - 1, lookAndSayV3(number, 0));
}

If the numbers should be stored in a List object, it can be done like

public static void lookAndSayUsingList(final String number, final int howMany, final List<String> resultList)
{
  resultList.add(number);
  if (resultList.size() < howMany)
  {
    lookAndSayUsingList(lookAndSayV3(number, 0), howMany, resultList);
  }
}
final List<String> resultList = new ArrayList<String>();
lookAndSayUsingList(number, howMany, resultList);
System.out.println(resultList);

If you prefer having returned result,

private static List<String> lookAndSayUsingList2(final String number, final int howMany, final List<String> list)
{
  list.add(number);
  if (list.size() < howMany)
  {
    return lookAndSayUsingList2(lookAndSayV3(number, 0), howMany, list);
  }
  return Collections.unmodifiableList(new ArrayList<String>(list));
}

The last line which returns an unmodifiable list object should use a new ArrayList object instead of directly using list.
Just making list unmodifiableList is not enough as the caller of this method can still modify the given parameter list
e.g.) Just have Collections.unmodifiableList(list); will result in

final List<String> resultList = new ArrayList<String>();
resultList.add(number);
final List<String> result = lookAndSayUsingList2(resultList, howMany);
// result.add("test"); // <- this does not work! runtime exception!
resultList.add("test"); // <- yet this does!!!
// Now the result has "test" at the end although it's unmodifiable List.
// It was modified using resultList.

If you don’t want to pass a List object, create another method and use it with the lookAndSayUsingList2() method.

public static List<String> lookAndSayUsingList2(final String number, final int howMany)
{
  final List<String> list = new ArrayList<String>();
  return lookAndSayUsingList2(number, howMany, list);
}
System.out.println(lookAndSayUsingList2(number, howMany));

Finally, using a Function object.

public interface LookAndSayFunction
{
  void apply(String number, int howMany);
}
final List<String> resultListFromFunctionObject = new ArrayList<String>();
new LookAndSayFunction() {
  @Override
  public void apply(final String number, final int howMany)
  {
    resultListFromFunctionObject.add(number);
    if (resultListFromFunctionObject.size() < howMany)
    {
      apply(lookAndSayV3(number, 0), howMany);
    }
  }
}.apply(number, howMany);

System.out.println(resultListFromFunctionObject);

Don’t want to get a mutable List object staying outside the function?

public interface Function1<T, R>
{
  R apply(T input);
}

public interface Function2<T1, T2, R>
{
  R apply(T1 input1, T2 input2);
}
final Function2<String, Integer, List<String>> anotherFunction =
  new Function2<String, Integer, List<String>>() {
    @Override
    public List<String> apply(final String number, final Integer howMany)
    {
      return new Function<List<String>>() {
        @Override
        public List<String> apply()
        {
          final List<String> resultList = new ArrayList<String>();
          return new Function1<String, List<String>>() {
            @Override
            public List<String> apply(final String number)
            {
              resultList.add(number);
              if (resultList.size() < howMany.intValue())
              {
                return apply(lookAndSayV3(number, 0));
              }
              return Collections.unmodifiableList(resultList);
            }
          }.apply(number);
        }
      }.apply();
    }
  };

System.out.println(anotherFunction.apply(number, howMany));

Or currying can be used.

final Function1<Integer, Function1<String, List<String>>> lookAndSayWithCurrying =
new Function1<Integer, Function1<String, List<String>>>() {
  @Override
  public Function1<String, List<String>> apply(final Integer howMany)
  {
    return new Function1<String, List<String>>() {
      @Override
      public List<String> apply(final String number)
      {
        final List<String> resultList = new ArrayList<String>();
        return new Function1<String, List<String>>() {
          @Override
          public List<String> apply(final String number)
          {
            resultList.add(number);
            if (resultList.size() < howMany.intValue())
            {
              return apply(lookAndSayV3(number, 0));
            }
            return Collections.unmodifiableList(resultList);
          }
        }.apply(number);
      }
    };
  }
};
System.out.println(lookAndSayWithCurrying.apply(howMany)
        .apply(number));

The function can be reused.

final Function1<String, List<String>> lookAndSayToGet10Elements = lookAndSayWithCurrying.apply(10);
System.out.println(lookAndSayToGet10Elements.apply(number));
System.out.println(lookAndSayToGet10Elements.apply(number));
Result:
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]
final Function1<String, List<String>> lookAndSayToGet5Elements = lookAndSayWithCurrying.apply(5);
System.out.println(lookAndSayToGet5Elements.apply(number));
Result:
[1, 11, 21, 1211, 111221]
System.out.println(lookAndSayToGet5Elements.apply("111221"));
Result:
[111221, 312211, 13112221, 1113213211, 31131211131221]
System.out.println(lookAndSayToGet5Elements.apply("21"));
Result:
[21, 1211, 111221, 312211, 13112221]
System.out.println(lookAndSayToGet5Elements.apply("1"));
Result:
[1, 11, 21, 1211, 111221]

If you want to fix the number and get different numbers of elements as the results from the look and say function,

final Function1<String, Function1<Integer, List<String>>> lookAndSayWithCurryingAndNumberFixed =
  new Function1<String, Function1<Integer, List<String>>>() {
    @Override
    public Function1<Integer, List<String>> apply(final String number)
    {
      return new Function1<Integer, List<String>>() {
        @Override
        public List<String> apply(final Integer howMany)
        {
          final List<String> resultList = new ArrayList<String>();
          return new Function1<String, List<String>>() {
            @Override
            public List<String> apply(final String number)
            {
              resultList.add(number);
              if (resultList.size() < howMany.intValue())
              {
                return apply(lookAndSayV3(number, 0));
              }
              return Collections.unmodifiableList(resultList);
            }
          }.apply(number);
        }
      };
    }
  };
final Function1<Integer, List<String>> lookAndSayWithNumberFixed = lookAndSayWithCurryingAndNumberFixed.apply("1");
System.out.println(lookAndSayWithNumberFixed.apply(3));
System.out.println(lookAndSayWithNumberFixed.apply(5));
System.out.println(lookAndSayWithNumberFixed.apply(10));

Results:

[1, 11, 21]
[1, 11, 21, 1211, 111221]
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]

Here are all the examples.

Results:

Using LookAndReadUsingForLoop: 
String result1 = number;
System.out.print(result1 + " ");
for (int i = 1; i < howMany; i++)
{
  result1 = LookAndSayUsingForLoop(result1);
  System.out.print(result1 + " ");
}
1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 
--------------------------------------------------------------------------------

Using lookAndSayV1: 
System.out.println(lookAndSay(howMany, number));
1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 
--------------------------------------------------------------------------------

Using lookAndSaV2: 
System.out.println(lookAndSay2(howMany, number));
1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 
--------------------------------------------------------------------------------

Using lookAndSaV3: 
System.out.println(lookAndSay3(howMany, number));
1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 
--------------------------------------------------------------------------------

Using lookAndSayUsingList: 
final List<String> resultList = new ArrayList<String>();
lookAndSayUsingList(number, howMany, resultList);
System.out.println(resultList);
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]
--------------------------------------------------------------------------------

Using lookAndSayUsingList2: 
System.out.println(lookAndSayUsingList2(number, howMany, new ArrayList<String>()));
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]
--------------------------------------------------------------------------------

Using another lookAndSayUsingList2 (without passing List): 
System.out.println(lookAndSayUsingList2(number, howMany))
--------------------------------------------------------------------------------

Using Function object: 
final List<String> resultListFromFunctionObject = new ArrayList<String>();
new LookAndSayFunction() {
  @Override
  public void apply(final String number, final int howMany)
  {
    resultListFromFunctionObject.add(number);
    if (resultListFromFunctionObject.size() < howMany)
    {
      apply(lookAndSayV3(number, 0), howMany);
    }
  }
}.apply(number, howMany);
System.out.println(resultListFromFunctionObject);
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]
--------------------------------------------------------------------------------

Using Function object with returned List object: 
final Function2<String, Integer, List<String>> anotherFunction = new Function2<String, Integer, List<String>>() {
  @Override
  public List<String> apply(final String number, final Integer howMany)
  {
    return new Function<List<String>>() {
      @Override
      public List<String> apply()
      {
        final List<String> resultList = new ArrayList<String>();
        return new Function1<String, List<String>>() {
          @Override
          public List<String> apply(final String number)
          {
            resultList.add(number);
            if (resultList.size() < howMany.intValue())
            {
              return apply(lookAndSayV3(number, 0));
            }
            return Collections.unmodifiableList(resultList);
          }
        }.apply(number);
      }
    }.apply();
  }
};
System.out.println(anotherFunction.apply(number, howMany));
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]

System.out.println(anotherFunction.apply(number, 5));
[1, 11, 21, 1211, 111221]

System.out.println(anotherFunction.apply(number, 7));
[1, 11, 21, 1211, 111221, 312211, 13112221]
--------------------------------------------------------------------------------

Using currying (number of elements fixed): 
final Function1<Integer, Function1<String, List<String>>> lookAndSayWithCurrying =
  new Function1<Integer, Function1<String, List<String>>>() {
    @Override
    public Function1<String, List<String>> apply(final Integer howMany)
    {
      return new Function1<String, List<String>>() {
        @Override
        public List<String> apply(final String number)
        {
          final List<String> resultList = new ArrayList<String>();
          return new Function1<String, List<String>>() {
            @Override
            public List<String> apply(final String number)
            {
              resultList.add(number);
              if (resultList.size() < howMany.intValue())
              {
                return apply(lookAndSayV3(number, 0));
              }
              return Collections.unmodifiableList(resultList);
            }
          }.apply(number);
        }
      };
    }
  };
lookAndSayWithCurrying.apply(howMany)
    .apply(number);
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]

final Function1<String, List<String>> lookAndSayToGet10Elements = lookAndSayWithCurrying.apply(10);
System.out.println(lookAndSayToGet10Elements.apply(number));
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]

System.out.println(lookAndSayToGet10Elements.apply(number));
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]

System.out.println(lookAndSayToGet10Elements.apply(number));
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]


final Function1<String, List<String>> lookAndSayToGet5Elements = lookAndSayWithCurrying.apply(5);
System.out.println(lookAndSayToGet5Elements.apply(number));
[1, 11, 21, 1211, 111221]

System.out.println(lookAndSayToGet5Elements.apply(number));
[1, 11, 21, 1211, 111221]

System.out.println(lookAndSayToGet5Elements.apply(number));
[1, 11, 21, 1211, 111221]

System.out.println(lookAndSayToGet5Elements.apply("111221"));
[111221, 312211, 13112221, 1113213211, 31131211131221]

System.out.println(lookAndSayToGet5Elements.apply("21"));
[21, 1211, 111221, 312211, 13112221]

System.out.println(lookAndSayToGet5Elements.apply("1"));
[1, 11, 21, 1211, 111221]
--------------------------------------------------------------------------------

Using currying (number fixed): 
final Function1<String, Function1<Integer, List<String>>> lookAndSayWithCurryingAndNumberFixed =
  new Function1<String, Function1<Integer, List<String>>>() {
    @Override
    public Function1<Integer, List<String>> apply(final String number)
    {
      return new Function1<Integer, List<String>>() {
        @Override
        public List<String> apply(final Integer howMany)
        {
          final List<String> resultList = new ArrayList<String>();
          return new Function1<String, List<String>>() {
            @Override
            public List<String> apply(final String number)
            {
              resultList.add(number);
              if (resultList.size() < howMany.intValue())
              {
                return apply(lookAndSayV3(number, 0));
              }
              return Collections.unmodifiableList(resultList);
            }
          }.apply(number);
        }
      };
    }
  };
final Function1<Integer, List<String>> lookAndSayWithNumberFixed = lookAndSayWithCurryingAndNumberFixed.apply("1");
System.out.println(lookAndSayWithNumberFixed.apply(howMany));
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]

System.out.println(lookAndSayWithNumberFixed.apply(3));
[1, 11, 21]

System.out.println(lookAndSayWithNumberFixed.apply(5));
[1, 11, 21, 1211, 111221]

System.out.println(lookAndSayWithNumberFixed.apply(10));
[1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]
Older posts

© 2014 Kevin's Blog

Theme by Anders NorenUp ↑

%d bloggers like this: