LinkedHashMap

LinkedHashMap is under Java Collection API and it implements Map interface. LinkedHashMap also works as same as HashMap with only 1 difference. Lets see the properties of LinkedHashMap class in Java

  • It works based on key and value as same as HashMap.
  • It implements Map interface and extends HashMap class, so that it acquires all properties of HashMap class. 
  • It can hold 1 null key and multiple null values. 
  • Only difference between HashMap and LinkedHashMap is interstion order. LinkedHashMap maintains the insertion order where as in HashMap its not. 

Now lets see simple example for LinkedHashMap and how to use it and also lets test the insertion order in both collection classes.


import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class LinkedHashMapTest {

 public static void main(String[] args) {
  
  Map<String, String> hm = new HashMap<String, String>();
  Map<String, String> lhm = new LinkedHashMap<String, String>();
  
  hm.put("1", "one"); 
  hm.put("2", "two");
  hm.put("3", "three");
  hm.put("4", "four");
  
  lhm.put("1", "one"); 
  lhm.put("2", "two");
  lhm.put("3", "three");
  lhm.put("4", "four");
  
  // Printing HashMap values.
  System.out.println("HasnMap Key and Value :::::::::::::::");
  Set<Entry<String, String>> set = hm.entrySet();
  Iterator<Entry<String, String>> itr = set.iterator();
  while(itr.hasNext()){
   Map.Entry<String, String> map = itr.next();
   System.out.println(map.getKey() +" : "+map.getValue());
  }
  
  // Printing LinkedHashMap values.
  System.out.println("HasnMap Key and Value :::::::::::::::");
  Set<Entry<String, String>> set1 = lhm.entrySet();
  Iterator<Entry<String, String>> itr1 = set1.iterator();
  while(itr1.hasNext()){
   Map.Entry<String, String> map1 = itr1.next();
   System.out.println(map1.getKey() +" : "+map1.getValue());
  }
 }
}


OUTPUT:


HasnMap Key and Value :::::::::::::::
3 : three
2 : two
1 : one
4 : four

HasnMap Key and Value :::::::::::::::
1 : one
2 : two
3 : three
4 : four


In above program we have added 4 values in HashMap and LinkedHashMap. Next when we print those key and value we can see the difference between both like HashMap insertion order not maintained while printing. Where as in LinkedHashMap its same as insertion order. 

Array in Java

Array in Java

Array is a simple Data Structure as same as which we have read in C, C++. If we need to describe then, "Array is a container which holds fixed no. of values of 1 data type (ie., If its Integer array then we can't store Character or String in it)". Size of the array must be defined at the time of array creation and its fixed until and unless if we try to re-create same array with different size. Lets see simple String array creation example in java.


public class ArrayTest {
 
 public static void main(String[] args) {
  
  // Creating Array with size 5
  String[] array = new String[5];
  
  array[0] = "java";
  array[1] = "J2EE";
  array[2] = "Servlet";
  array[3] = "JSP";
  array[4] = "Web Services";
  
  // Which gives runtime exception
  // ArrayIndexOutOfBoundsException
  //array[5] = "java";
  
  System.out.println("array[0] - "+array[0]);
  System.out.println("array[1] - "+array[1]);
  System.out.println("array[2] - "+array[2]);
  System.out.println("array[3] - "+array[3]);
  System.out.println("array[4] - "+array[4]);
 }
}


OUTPUT: 


array[0] - java
array[1] - J2EE
array[2] - Servlet
array[3] - JSP
array[4] - Web Services


As we seen in above example we can't assign values to "array[5]", since we have created array with the size of 5 and we are trying to store value beyond its size. So we will get run-time exception call ArrayIndexOutOfBoundsException.


Multi-Dimensional Array:

Above we have seen about single dimensional array creation with example. In Java we can use Multi-Dimensional array also as like below.


public class ArrayTest {
 
 public static void main(String[] args) {
  
  String names[][] = { {"thread", "array", "collection"}, 
        {"jsp", "servlet"}, 
        {"SOAP", "RESTFull"} 
          };
  
  System.out.println("names[0][0] - "+ names[0][0]);
  System.out.println("names[1][1] - "+ names[1][1]);
  System.out.println("names[2][0] - "+ names[2][0]);
  System.out.println("names[0][3] - "+ names[0][2]);
  
 } 
}


OUTPUT:


names[0][0] - thread
names[1][1] - servlet
names[2][0] - SOAP
names[0][3] - collection



Array Types:

Not only String we can create array with all primitve and non-primitive data types in Java as like below. 


int[] _int = new int[5];
char[] _char = new char[2];
float[] _flat = new float[4];
Integer[] _Integer = new Integer[5];
Boolean[] _Boolean = new Boolean[4];




Copying array values to another array:

System class method arraycopy() is used to copy array values from 1 array (source) to another array (destination). Both source and destination array must be same data type. arraycopy() method contains 5 parameters like
src - Source array
srcPos - Source array position to copy
dest - Destination array
destPos - Destination array position to be copied 
length - Length of array to copy 

Below is a simple example to copy array value from 1 array to another array.


public class ArrayTest {
 
 public static void main(String[] args) {
  
  int[] _intSrc = new int[]{0,11,12,13,14,15,16,17,18,19};
  
  int[] _intDes = new int[5];
  
  _intDes[0] = 99;
  
  // Copying values from 11 to 14
  System.arraycopy(_intSrc, 1, _intDes, 1, 4);
  
  for (int val : _intDes) {
   System.out.println(val);
  }
 } 
}


OUTPUT:


99
11
12
13
14



Another way of copying values from 1 array to another array using java.util.Arrays() class. Method called copyOfRange() used to copy specific array elements to another array same like below example code.


import java.util.Arrays;

public class ArrayTest {
 
 public static void main(String[] args) {
  
  int[] _intSrc = new int[]{0,11,12,13,14,15,16,17,18,19};
  
  // Copying from _intSrc (Range index 2 to 7)
  int[] _intDes = Arrays.copyOfRange(_intSrc, 2, 7);
  
  for (int val : _intDes) {
   System.out.println(val);
  }
 } 
}


OUTPUT:


12
13
14
15
16










Split() in Java

 
Split in Java

In our earlier tutorial we have seen about String Tokenizer class in Java. And we have given Split method from String class which will be an alternate since String Tokenizer is legacy class. So its recommended to use split method from String class instead of StringTokenizer. So lets see whats the use if split method and how we can use in Java by using simple example. 

Split method used to search for the match as specified in the argument and splits the string and stores into an String array. There are 2 types of split methods in String class,

String str = "Hello how are you";
String arr[] = str.split(" ");

will give output as below, since we are splitting by space " "
Hello
how
are
you



String str = "Hello how are you";
String arr[] = str.split(" ", 2);

will give output as below, here we are requesting to split the string with the array size as 2. so remaining complete string will be stored in last array as below
Hello
how are you


Lets see simple java example with their output.


public class SplitTest {
 
 public static void main(String[] args) {
  String str = "Hello how are you";
  
  String arr[] = str.split(" ");
  for (String string : arr) {
   System.out.println(string);
  }
  
  System.out.println("-------------------------------");
  
  String arr1[] = str.split(" ",3);
  for (String string : arr1) {
   System.out.println(string);
  }
 }
}


OUTPUT:


Hello
how
are
you
-------------------------------
Hello
how
are you






String Tokenizer in Java


String Tokenizer in Java

In most of the older application we will be seen String Tokenizer class used for operations like splitting words or text from a given String or line. The String Tokenizer class allows user to break a String into tokens based on the input parameters. By default String Tokenizer will split the String and gives the token based on space character else we can provide our delimit as parameter. Lets see few String Tokenizer constructor parameters with their output.

StringTokenizer tok = new StringTokenizer("Hello how are you");
will give output as below, since space (" ") is a default delimiter
Hello
how
are
you

StringTokenizer tok = new StringTokenizer("Hello|how|are|you", "|");
will give output as below, since we have delimit as "|"
Hello
how
are
you

StringTokenizer tok = new StringTokenizer("Hello|how|are|you", "|", true);
will give output as below, true gives the delimiter along with tokens 
Hello
|
how
|
are
|
you

Lets see simple example of using String Tokenizer class in Java.


import java.util.StringTokenizer;

public class StringTokenizerTest {
 
 public static void main(String[] args) {
  
  StringTokenizer tok = new StringTokenizer("Hello how are you");
  while(tok.hasMoreTokens()){
   System.out.println(tok.nextElement());
  }
  
  System.out.println("-------------------------------");
  
  tok = new StringTokenizer("Hello|how|are|you", "|");
  while(tok.hasMoreTokens()){
   System.out.println(tok.nextElement());
  }
  
  System.out.println("-------------------------------");

  tok = new StringTokenizer("Hello|how|are|you", "|", true);
  while(tok.hasMoreTokens()){
   System.out.println(tok.nextElement());
  }
 }
}


OUTPUT:


Hello
how
are
you
-------------------------------
Hello
how
are
you
-------------------------------
Hello
|
how
|
are
|
you




Alternate:

String Tokenizer is from legacy class and because of compatibility reasons recommended to use "split" method from String class. Lets see this "split" method in our next tutorial



Fetch Windows OS, System, Memory, BIOS, Network, Hard Drive details using Java code

Fetch Windows System details

In lot of applications or real time programs we may in need of finding the Windows system information's like

1. Windows system properties like fetching Windows OS version, JVM version, OS architecture, Java Version, OS name, Windows user name etc.,
2. Fetching Windows BIOS serial number.
3. Fetching memory details like 

  • Virtual Memory Size 
  • Free Physical Memory Size 
  • Free Swap Space Size 
  • Process CPU Time 
  • Total Physical Memory Size 
  • Total Swap Space Size 

4. Fetching network interface and Adapter details 
5. Fetching system hard drive details like each drive total and free space. 

Lets see a Java code which will fetch a complete information as we discussed above.


import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Scanner;

public class FindWindows {

 public static void main(String[] args) {
  
  System.out.println("\n *********************** SYSTEM DETAILS ***********************  ");
  systemDetails();
  System.out.println("\n *********************** MEMORY DETAILS ***********************  ");
  getMemoryDetails();
  System.out.println("\n *********************** BIOS SERIAL NUMBER ***********************  ");
  getBIOSSerialNumber();
  System.out.println("\n *********************** NETWORK DETAILS ***********************  ");
  getNetworkDetails();
  System.out.println("\n *********************** HARD DRIVE DETAILS ***********************  ");
  getHardDriveDetails();
 }

 public static void systemDetails() {
  System.getProperties().list(System.out);
 }

 private static void getMemoryDetails() {
  
  OperatingSystemMXBean osMemDetails = ManagementFactory
    .getOperatingSystemMXBean();
  
  for (Method method : osMemDetails.getClass().getDeclaredMethods()) {
   method.setAccessible(true);
   long value = 0;
   try {
    value = method.invoke(osMemDetails) != null ? Long
      .parseLong(method.invoke(osMemDetails).toString()) : 0;
   } catch (Exception e) {
    e.printStackTrace();
   }
   
   System.out.println(method.getName() + " : " + value+" Bytes");
  }
  
  // no. of processors available
     System.out.println("No. of processors : " + Runtime.getRuntime().availableProcessors());
 }

 public static void getBIOSSerialNumber() {
  try{
   Process process = Runtime.getRuntime().exec(
     new String[] { "wmic", "bios", "get", "serialnumber" });
   
   process.getOutputStream().close();
   Scanner sc = new Scanner(process.getInputStream());
   String property = sc.next();
   String serial = sc.next();
   
   System.out.println(property + ": " + serial);
  }catch (IOException e) {
   e.printStackTrace();
  }
 }

 public static void getNetworkDetails() {
  try{
   Enumeration<NetworkInterface> netIntList = NetworkInterface
     .getNetworkInterfaces();
   while (netIntList.hasMoreElements()) {
    NetworkInterface netInt = netIntList.nextElement();
    System.out.println(netInt.getName() + " : " + netInt.getDisplayName());
   }
  }catch (IOException e) {
   e.printStackTrace();
  }
 }

 public static void getHardDriveDetails() {
  File[] drives = File.listRoots();
  for (int i = 0; i < drives.length; i++) {
   System.out.println("Drive :" + drives[i]);
   File drive = new File(drives[i].toString());
   long totalDriSpace = drive.getTotalSpace();
   long freeSpace = drive.getFreeSpace();
   
   totalDriSpace = (totalDriSpace/1024/1024/1024); // Converting Bytes to GB
   freeSpace = (freeSpace/1024/1024/1024); // Converting Bytes to GB
   
   System.out.println("Total Drive Size : " + totalDriSpace+" GB");
   System.out.println("Free Space       : " + freeSpace+" GB");
   System.out.println("-------------------------------------");
  }
 }
}


OUTPUT:


 *********************** SYSTEM DETAILS ***********************  
-- listing properties --
java.runtime.name=Java(TM) SE Runtime Environment
sun.boot.library.path=C:\Program Files\Java\jre6\bin
java.vm.version=16.3-b01
java.vm.vendor=Sun Microsystems Inc.
java.vendor.url=http://java.sun.com/
path.separator=;
java.vm.name=Java HotSpot(TM) Client VM
file.encoding.pkg=sun.io
user.country=US
sun.java.launcher=SUN_STANDARD
sun.os.patch.level=Service Pack 1
java.vm.specification.name=Java Virtual Machine Specification
user.dir=D:\workspace\java\MyProject
java.runtime.version=1.6.0_20-b02
java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironment
java.endorsed.dirs=C:\Program Files\Java\jre6\lib\endorsed
os.arch=x86
java.io.tmpdir=C:\Users\anand\AppData\Local\Temp\
line.separator=

java.vm.specification.vendor=Sun Microsystems Inc.
user.variant=
os.name=Windows 7
sun.jnu.encoding=Cp1252
java.library.path=C:\Program Files\Java\jre6\bin;.;C:\W...
java.specification.name=Java Platform API Specification
java.class.version=50.0
sun.management.compiler=HotSpot Client Compiler
os.version=6.1
user.home=C:\Users\anand
user.timezone=
java.awt.printerjob=sun.awt.windows.WPrinterJob
file.encoding=Cp1252
java.specification.version=1.6
user.name=anand
java.class.path=D:\workspace\java\MyProject\bin;D:\wo...
java.vm.specification.version=1.0
sun.arch.data.model=32
java.home=C:\Program Files\Java\jre6
java.specification.vendor=Sun Microsystems Inc.
user.language=en
awt.toolkit=sun.awt.windows.WToolkit
java.vm.info=mixed mode, sharing
java.version=1.6.0_20
java.ext.dirs=C:\Program Files\Java\jre6\lib\ext;C:...
sun.boot.class.path=C:\Program Files\Java\jre6\lib\resour...
java.vendor=Sun Microsystems Inc.
file.separator=\
java.vendor.url.bug=http://java.sun.com/cgi-bin/bugreport...
sun.cpu.endian=little
sun.io.unicode.encoding=UnicodeLittle
sun.desktop=windows
sun.cpu.isalist=pentium_pro+mmx pentium_pro pentium+m...

 *********************** MEMORY DETAILS ***********************  
getCommittedVirtualMemorySize : 41385984 Bytes
getCommittedVirtualMemorySize0 : 41385984 Bytes
getFreePhysicalMemorySize : 794828800 Bytes
getFreeSwapSpaceSize : 4186632192 Bytes
getProcessCpuTime : 93600600 Bytes
getTotalPhysicalMemorySize : 2147483647 Bytes
getTotalSwapSpaceSize : 4294967295 Bytes
initialize : 0 Bytes
No. of processors : 2

 *********************** BIOS SERIAL NUMBER ***********************  
SerialNumber: 993D1BS

 *********************** NETWORK DETAILS ***********************  
lo : Software Loopback Interface 1
net0 : WAN Miniport (SSTP)
net1 : WAN Miniport (L2TP)
net2 : WAN Miniport (PPTP)
ppp0 : WAN Miniport (PPPOE)
eth0 : WAN Miniport (IPv6)
eth1 : WAN Miniport (Network Monitor)
eth2 : WAN Miniport (IP)
ppp1 : RAS Async Adapter
eth3 : Intel(R) 82567LM Gigabit Network Connection
net3 : Teredo Tunneling Pseudo-Interface
net4 : Intel(R)  WiFi Link 5300 AGN
eth4 : WAN Miniport (IP) - Juniper Network Agent Miniport
eth5 : Intel(R)  WiFi Link 5300 AGN - Juniper Network Agent Miniport
net5 : Juniper Networks Virtual Adapter Manager
eth6 : Juniper Networks Virtual Adapter
eth7 : Juniper Networks Virtual Adapter - Juniper Network Agent Miniport
eth8 : Juniper Networks Virtual Adapter #2
eth9 : Juniper Networks Virtual Adapter #2 - Juniper Network Agent Miniport
eth10 : Juniper Networks Virtual Adapter #3
eth11 : Juniper Networks Virtual Adapter #3 - Juniper Network Agent Miniport
eth12 : Juniper Networks Virtual Adapter #4
eth13 : Juniper Networks Virtual Adapter #4 - Juniper Network Agent Miniport
net6 : WAN Miniport (IKEv2)
eth14 : Juniper Network Connect Virtual Adapter
eth15 : Juniper Network Connect Virtual Adapter - Juniper Network Agent Miniport
net7 : Microsoft 6to4 Adapter
net8 : Microsoft ISATAP Adapter
net9 : Microsoft ISATAP Adapter #3
net10 : Microsoft ISATAP Adapter #2
net11 : Microsoft ISATAP Adapter #4
eth16 : Intel(R) 82567LM Gigabit Network Connection-QoS Packet Scheduler-0000
eth17 : Intel(R) 82567LM Gigabit Network Connection-WFP LightWeight Filter-0000
eth18 : Intel(R)  WiFi Link 5300 AGN - Juniper Network Agent Miniport-QoS Packet Scheduler-0000
eth19 : Intel(R)  WiFi Link 5300 AGN - Juniper Network Agent Miniport-WFP LightWeight Filter-0000
eth20 : WAN Miniport (Network Monitor)-QoS Packet Scheduler-0000
eth21 : Juniper Network Connect Virtual Adapter - Juniper Network Agent Miniport-QoS Packet Scheduler-0000
eth22 : WAN Miniport (IPv6)-QoS Packet Scheduler-0000
net12 : Intel(R)  WiFi Link 5300 AGN-Native WiFi Filter Driver-0000
eth23 : Juniper Network Connect Virtual Adapter - Juniper Network Agent Miniport-WFP LightWeight Filter-0000
eth24 : WAN Miniport (IP) - Juniper Network Agent Miniport-QoS Packet Scheduler-0000

 *********************** HARD DRIVE DETAILS ***********************  
Drive :C:\
Total Drive Size : 68 GB
Free Space       : 27 GB
-------------------------------------
Drive :D:\
Total Drive Size : 80 GB
Free Space       : 72 GB
-------------------------------------
Drive :E:\
Total Drive Size : 0 GB
Free Space       : 0 GB
-------------------------------------
Drive :H:\
Total Drive Size : 4191 GB
Free Space       : 113 GB
-------------------------------------
Drive :M:\
Total Drive Size : 78 GB
Free Space       : 48 GB
-------------------------------------
Drive :N:\
Total Drive Size : 78 GB
Free Space       : 48 GB
-------------------------------------