Skip to main content

Posts

Showing posts with the label Java Program

Program : How to find if given String is palindrome in Java?

The blow program is used to check the string whether it is a palindrome or not. Based on the position of the character in the string we are checking for the same. The simplest way we are following that we are creating one more string from the given string and but in reverse order. After that we are checking that equality of both the strings. import java.util.Scanner; public class StringCheckPalindrome {  public static void main(String args[]) {   Scanner sc = new Scanner(System.in);   try {    String str;    String rev = "";    System.out.println("Enter a string:");    str = sc.nextLine();    int length = str.length();    for (int i = length - 1; i >= 0; i--)     rev = rev + str.charAt(i);    if (str.equals(rev))     System.out.println(str + " is a palindrome");    else     System.o...

Program : How to remove duplicate elements from ArrayList in Java?

The simplest approach to remove repeated objects from ArrayList is to copy them to a Set e.g. HashSet and then copy it back to ArrayList. This will remove all duplicates without writing any more code. One thing to noted is that, if original order of elements in ArrayList is important for you, as List maintains insertion order, you should use LinkedHashSet because HashSet doesn't provide any ordering guarantee. If you are using deleting duplicates while iterating, make sure you use Iterator's remove() method and not the ArrayList one to avoid ConcurrentModificationException. In this tutorial we will see this approach to remove duplicates. import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /**  * Java Program to remove repeated elements from ArrayList  *  * @author Gaurav  */ public class ProgramArrayListDuplicate {  public static void main(String args[]) {   // creating an ArrayList   List...