Sunday 24 November 2013

Convert List to Set in java

Lets see how to convert the ArrayList to Set in java.

Class name:  ListToSet.java

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ListToSet{
   public static void main(String[] args){

  List<String> myList = new ArrayList<String>();
  myList.add("one");
  myList.add("two");
  myList.add("three");
 
  //Convert List to Set
  Set<String> foo = new HashSet<String>(myList);
  System.out.println("Size of new set is: " + foo.size());
   }
}

OUTPUT:
Size of new set is: 3

Convert int to BigInteger in Java

Lets see how to convert the int value to BigInteger in java.

Class name:  IntToBiginteger.java

import java.util.*;
import java.math.BigInteger;

public class IntToBiginteger{
   public static void main(String[] args){
  BigInteger result = BigInteger.valueOf(5);
  System.out.println("Big int value is: " + result);
   }
}

OUTPUT:
Big int value is: 5

Search a word in a String using Java IndexOf


We can search for a word in any String object using indexOf() method which returns the position of the word within the string. If the word or letter is not found then it returns -1.

Class name:  FindTheWord.java
import java.util.*;

public class FindTheWord {
public static void main(String[] args) {  
String strOrig = "Hello world";
     int intIndex = strOrig.indexOf("world");
     if(intIndex == - 1){
        System.out.println("world not found");
     }else{
        System.out.println("Found world at index " + intIndex);
     }
}
}

OUTPUT:
Found world at index 6