Posts

Showing posts with the label Java

Using foreach method with list in Java 8

This blog post is about using foreach method with list in Java 8. Foreach method can be used to easily iterate a list. Check my previous post to see how to iterate foreach method with map in Java 8 . The program to iterate list using foreach method is as follows: import java.util.ArrayList; import java.util.List; /* * Java program to demonstrate the use of forEach method in List */ public class ForEachList { public static void main(String[] args) { List<String> usStates = new ArrayList<>(); usStates.add( "California" ); usStates.add( "New York" ); usStates.add( "New Mexico" ); usStates.add( "Pennsylvania" ); usStates.add( "New Jersey" ); // iterating the List through normal method System.out.println( "***Iterating the list through normal method***\n" ); for (String states:usStates) { ...

Foreach method in Java 8

This blog post is about foreach method in Java 8. This method is used to iterate over collections. The main use I found in this method is to iterate maps in Java. The normal syntax used in iterating a map in Java is as follows: for (Map.Entry<String, String> entry : usStates.entrySet()) Here 'usStates' is the name of the map. This syntax is slightly difficult to remember. Using foreach method, we can iterate the map as follows; usStates.forEach((k,v)-> { //Easy to iterate the map This is explained in a program as shown below: import java.util.HashMap; import java.util.Map; public class ForEachMap { public static void main(String a[]) { Map<String, String> usStates = new HashMap<>(); usStates.put( "California" , "Sacramento" ); usStates.put( "Kansas" , "Topeka" ); usStates.put( "New York" , "Albany" ); usStates.p...

Java program to find the highest product of 3 elements in an array

This blog post is about java program to find the highest product of 3 elements in an array. Introduction: When this question is asked, the usual solution which comes to our mind will be multiplying each element with other elements and finding the maximum product out of those, which is the brute force solution. The function for brute force  approach is as follows: /* * Method to return the highest product of three elements. * return type: Integer * input: int arr[] */ public static Integer returnHighestProduct( int arr[]) { if ((arr== null )||(arr.length<3)) { return null ; } else { int product = Integer.MIN_VALUE; for ( int i=0;i<arr.length;i++) { for ( int j=i+1;j<arr.length;j++) { for ( int k=j+1;k<arr.length;k++) { int max_product = arr[i]*arr[j]*arr[k]; if (max_product>=product) { product = max_product; } } } } return product; } } ...

Java program to check if an array is bitonic

This blog post is about a java program to check whether an array is bitonic or not. Introduction A bitonic array for this program is defined as an array of length 'N" and for an index 'K' in this array, where 0<K<N-1, the sequence from 0 to K should be increasing order and from K to N-1 should be in decreasing order. Eg: {1,5,3}, {1,2,3,10,9,8} Solution From starting position, find the element K , upto which the sequence is in increasing order. Check whether the sequence is in decreasing order from K to last element in the array. If not return false. Return true after execution of the method. Program package techjourney.programs; /** * Created by Sujith Mohan on 7/20/2015. * This java program is for checking whether a given array is bitonic or not. * A bitonic array for this program is defined as an array of length 'N' and * for an index 'K' in this array, where 0<K<N-1, the sequence from 0 to K should be * incre...

Java program to convert mobile number pad to characters

Image
This post is about Java program to convert mobile number pad to characters. Example ========= Here is an image of mobile phone num pad. For every numbers except 1, there are certain character value associated with that. # is used to separate the letters. If the user presses 44#44, it should print HH Logic of the program ================ A hashmap is used to store the number and its corresponding characters. If the user presses the number n times before pressing # , the nth character is selected from the hashmap. if n is greater than number of characters, select the character which is at the position (n mod number of characters) Program ======== The java program is as follows: import java.util.HashMap; public class MobilePhoneNumPadToCharacters { public static void main(String[] args) { System.out.println(returnWords( "222#2#8" )); //CAT System.out.println(returnWords( "5555#2#888888#2222" )); /...

Java program to return the first non repeated character in a string

Image
This post is about java program to return the first non repeated character in a string. Example: Given a string "hhello", It should return 'e' as the first non repeated character. Logic of the program: Using a linked hash map will solve this program. All the characters[a-z] can be stored in a linked hash map as key and value should be corresponding to be number of occurrence of each character.  To return the first non repeated char, just iterate the linked hash map and return first key having value as 1. Program: package com.techjourney; import java.util.LinkedHashMap; import java.util.Map; /** * Created by Sujith Mohan on 6/4/2015. */ public class FirstNonRepeatedChar { public static char returnFirstNonRepeatedChar(String str) { if (str== null ) throw new NullPointerException(); if (str.equals( "" )) return '\0' ; LinkedHashMap<Character, Integer> map = ...

Java program to check if a string is pangram

Hi everyone, in this blog, I will be writing about a java program to check whether a string is pangram or not. Pangrams are words or sentences containing every letter of alphabet at least once. Most commonly used example of pangram is " A quick brown fox jumps over the lazy dog. " Logic of the program Initialize a string testString as "abcdefghijklmnopqrstuvwxyz" Loop the input string for every character, and replace those character in testString with empty character. If testString is an empty string, then input string is Pangram The program for pangram is as follows: package com.blog.techjourney; public class Pangram { public static Boolean checkForPangram(String str) { int len = str.length(); //test string for testing all characters are present in the given string String testString = "abcdefghijklmnopqrstuvwxyz" ; for ( int i=0;i<len;i++) { char chars =str.charAt(i); //Converting the char to String a...

Java program to check if two elements of an array adds to the given sum

Hi everyone, in this blog post, I will be discussing about a famous java program, which is to check if two elements of an array adds to the given sum. Problem Given an array with elements and a sum. Check whether any 2 elements of the array adds to the given sum. Return true if the sum is present, else return false. Example Given an array {1,2,4}. The array should return true for the sum 5 and false for 4. Solution The basic solution which comes to everyone's mind would be to check each element with each other elements for the given sum. But the total time complexity in doing that will be O(n^2). We will approach the problem in a much easier way. The logic for that is as follows: Sort the given array in ascending order. Create two variables, one which tracks from the first position of array ( pos_first ) and other which tracks from the last position of the array ( pos_last ). While pos_first is less than pos_last , do the below steps. Add the elements corr...

Java program to change the elements of the array with the product of remaining elements

Hi Everyone, In this blog post I will be discussing about an interesting program, which is to change the " elements of the array with the product of remaining elements ". This program is really interesting as well as tricky. If an array contains 0, the product of all the elements in the array will be 0. For eg: If an array is [0,1,2], after performing the algorithm, it will be [2,0,0]. Logic The logic of the program is as follows: Initialize an integer variable product = 1. (This variable is used to store the product of all elements of array) Initialize an integer variable countOfZeros =0 Find the product of all the non-zero elements in the array as well as count the number of zero's in the array. If countOfZeros is greater than or equal to 2, then change all the elements of array to 0. If countOfZeros is 1, then change all non zero elements to 0 and 0 to product . If countOfZeros is 0, then change all elements to product /(element). IDE used - Intel...

Java program to get the Next Greater Element in an array

Hi Everyone, it's been a long time since I have made a post. So here goes one. In this blog post, I will be writing about a Java program to get the next greater element in an array. Expected output : For every element in the array, print the number which is the next greater to the element and which occurs after the element in position. If greater element is not found print -1. Logic of the program : Assign an element next greater value, " ngv "as -1. For every element " i " in the array, loop from the next element till last element. In the loop, if an element is greater than " i " and " ngv " is -1 , assign " ngv " as the element. In the loop, if an element is greater than " i " and " ngv " is not -1, check whether " ngv " greater than that element. If so, assign " ngv " as the element. Return " ngv ". The java program is as follows: package  com.blog.techjourney;...

Java program to access an URL

Hi Everyone, in this blog post I will be writing a java program to access an URL. The Java program to connect to an URL is as follows: package com.blog.techjourney; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class AccessURL { public static void main(String[] args) { String url = "http://sujithforu.blogspot.com/" ; String fakeurl = "http://thisisanincorrecttypeofurl.com/" ; System.out.println( " Connecting to existing url - " +url); getURLResponse(url); System.out.println(); System.out.println( " Connecting to fake url - " +fakeurl); getURLResponse(fakeurl); } public static void getURLResponse(String str) { URL url; URLConnection urlConnection; HttpURLConnection httpConnection = null ; try { url = new URL(str); urlConnection = url.openConnection(); urlConnection.co...

Removing duplicates and ordering a list using java

Hi everyone, in this blog post, I will be writing about ' How to remove duplicates and order a list using java '. For removing duplicates in a list, we can put all the contents of the list to a set. For ordering the set, we can use an implementation of treeset. So in general, to remove duplicates and order a set, we could do by putting all the contents of the list to a treeset. Please refer my post about sets to understand more about treesets. Here is the java program to remove duplicates and order a list. package  com.blog.techjourney; import  java.util.ArrayList; import  java.util.List; import  java.util.Set; import  java.util.TreeSet; public   class  removeDuplicatesAndOrder {      public   static   void  main(String[] args) {         List  countries =  new  ArrayList ();          ...

Finding third largest element in an array using Java

Hi everyone, in this blog post, I am writing a Java program to find the third largest element in an array. When we are asked to write a program about finding the third largest element in an array, the trivial solution which comes to our mind is sorting the array and returning the third element from the end. But sorting an array is of time complexity O(nlogn) and   a program always requires to minimize the total time complexity and space complexity. We can do the above program in time O(n). The logic of the program is as follows: Initialize three variables as firstLargest , secondLargest and thirdLargest to Integer.MIN_VALUE Iterate the loop of elements in the array. For each number , check the following steps If firstLargest is less than the number , assign thirdLargest to secondLargest , secondLargest to firstLargest and firstLargest to the number . Else if secondLargest is less than the number and if number not equal to firstLargest , then assign thirdLargest ...