Interview Question

Leave a comment

July 20, 2014 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

The (complicated) answer is:

public static void main(String... args) {
		IntStream.rangeClosed(1, 100).mapToObj(i -> {
		List res = new ArrayList<>();
		if (i % 3 == 0) {
			res.add("Hello");
		}
		if (i % 5 == 0) {
			res.add("World");
		}
		if (res.isEmpty()) {
			res.add(Integer.toString(i));
		}
		return res;
	}).map(s -> StringUtils.join(s, " ")).forEach(out::println);
}
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: