Interview Question (cont.)

Leave a comment

January 4, 2015 by huionn

A simple Java interview question:

For 1 to 100,

  1. if the number is the multiple of 3, then print ‘Hello’
  2. if the number is the multiple of 5, then print ‘World’
  3. if the number is the multiple of 3 and 5 , then print ‘Hello World’
  4. Otherwise, print the number

… in asynchronous Reactive Programming style.

public class RxHelloWorld {
  public static void main(String... args) {

    Observable obs = Observable.create(subsriber -> new Thread(
        () -> {
          for (int i = 1; i <= 100; i++) {
            if (subsriber.isUnsubscribed()) {
              return;
            }
            subsriber.onNext(i);
          }

          if (!subsriber.isUnsubscribed()) {
            subsriber.onCompleted();
          }
        }).start());

    obs.subscribe(new MyObserver());
  }

  private static String transform(Integer i) {
    if (i % 3 == 0 && i % 5 == 0) {
      return "Hello World";
    }
    if (i % 3 == 0) {
      return "Hello";
    }
    if (i % 5 == 0) {
      return "World";
    }
    return "" + i;
  }

  private static class MyObserver extends Subscriber {

    @Override
    public void onCompleted() {
      System.out.println("-- done --");
    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public void onNext(Integer i) {
      System.out.println(transform(i));
    }
  }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: