One machine can do the work of fifty ordinary men. No machine can do the work of one extraordinary man

Tuesday, January 1, 2019

How to take input from user in Java

This is one of the common and frequently asked question in Java language. There are few ways to get the user inputs from user via a keyboard.
  • Scanner
  • BufferedReader and InputStreamReader
  • Console
  • DataInputStream (This is deprecated)

Scanner

This is the easiest way to get keyboard inputs from the user. Java Scanner class comes under the java.util package. Normally scanner tokenize the input from the white spaces as a default delimiter. An another advantage of the Scanner is you don't have to write another like to convert the value into a different (required) data format.

import java.util.Scanner;

// Set the default input stream (keyboard) to the scanner object.
Scanner scan = new Scanner(System.in);

// Default next method returns you the value as a String.
String s = scan.next();

// Use the nextInt(), nextDouble() like methods to read the input and parse that directly to a required data format.

int i = scan.nextInt();

// Can read the whole line at once.
String s = scan.nextLine();

Buffered Reader and Input Stream Reader

These two classes comes under the java.io package.

import java.io.BufferedReader; 
import java.io.InputStreamReader; 

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 

String s = br.readLine(); 

int i = Integer.parseInt(br.readLine());

Console

The Console class is also comes under the java.io package.

import java.io.Console;
Console console = System.console();

String s = console.readLine();

Monday, December 31, 2018

How to split a String by space (any white space)

The String splitting is a very common requirement in any programming language. In java it is very much straight forward since there is a split() method in String. Normally what we do is provide the delimiter to the split method and get the tokens into a String array.

But most of beginners don't know we can pass regular expression as a delimiter.

Here I am using a regular expression as a delimiter to split the String by any white space regardless it is a tab, space, multiple tabs or spaces.

str = "This is     the String with    different white spaces";
String[] splited = str.split("\\s+");

Saturday, December 29, 2018

Iterate Map in Java 8


Java 1.8 is a huge bump in the programming world with the introduction of great features sometimes object oriented programmers didn't even imagine. They introduced some of the functional programming features into Java world such as functional interfaces, lamda functions and that helps programmers to use object oriented concepts in a better way.

Sometimes iterating through a collection such as a map or list is a headache for a programmer since there can be concurrent issues.


The most famous way of doing it is using an Iterator (This is the best way before 1.8).

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Main {

public static void main(String[] args) {

// Creating students.
Student s01 = new Student("001", "Steven");
Student s02 = new Student("002", "Mathews");

// Creating a map.
Map<String, Student> students = new HashMap<>();

// Populating the map.
students.put(s01.getId(), s01);
students.put(s02.getId(), s02);

// Get the Iterator.
Iterator<Map.Entry<String, Student>> iterator = students.entrySet().iterator();

// Iterator through the map using the iterator.
while(iterator.hasNext()) {

Map.Entry<String, Student> studentEntry = iterator.next();

// Can retrieve the id if required.
String id = studentEntry.getKey();

// Retrieve the student from the map entry.
Student student = studentEntry.getValue();

System.out.println(student);

}
}


static class Student {

private String id;
private String name;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Student(String id, String name) {
this.id = id;
this.name = name;
}

@Override
public String toString() {
return "Student{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
}


The simplest way is a for loop.


public static void main(String[] args) {
// Creating students.
Student s01 = new Student("001", "Steven");
Student s02 = new Student("002", "Mathews");

// Creating a map.
Map<String, Student> students = new HashMap<>();

// Populating the map.
students.put(s01.getId(), s01);
students.put(s02.getId(), s02);

// Iterator through the entry set.
for(Map.Entry<String, Student> entry: students.entrySet()) {

// Accessing the entry.
Student student = entry.getValue();

System.out.println(student);
}
}

Now with the introduction of lamda functions, we have a better way of doing this.

public static void main(String[] args) {
// Creating students.
Student s01 = new Student("001", "Steven");
Student s02 = new Student("002", "Mathews");

// Creating a map.
Map<String, Student> students = new HashMap<>();

// Populating the map.
students.put(s01.getId(), s01);
students.put(s02.getId(), s02);

// Use forEach method for a collection in Java 8.
students.entrySet().forEach((studentEntry) -> {

// Access the entry of the map.
Student student = studentEntry.getValue();

System.out.println(student);

});
}


Hope this helps you, please let me know your comments about the post.