Posts

Showing posts from September, 2024

3 Ways to Iterate elements in hashmap - java

  import java.util.HashMap ; import java.util.Map ; public class hashmapIterations { public static void main (String[] args) { HashMap<String , String> hm = new HashMap<String , String>() ; hm.put( "a" , "A" ) ; hm.put( "b" , "B" ) ; hm.put( "c" , "C" ) ; System. out .println(hm) ; hm.forEach((k , v)-> System. out .println(k+ ":" +v)) ; //from lambda for (Map.Entry<String , String> entry : hm.entrySet()){ //from entry set System. out .println(entry.getKey()) ; } for (String s: hm.keySet()){ //from key set to print keys System. out .println(s) ; } for (String s: hm.values()){ //from values to print values System. out .println(s) ; } } }

convert String into int without using parse

  public class test1 { public static void main (String[] args) { String abc = "123" ; int t= 0 ; char arr1[] = abc.toCharArray(); for ( int i= 0 ;i<arr1. length ;i++){ t = t* 10 + (arr1[i]- '0' ); } System. out .println(t); } }

Shift all zero's to the end of array

  public class move_zero_to_last { public static void main (String[] args) { int arr[]={ 1 , 3 , 0 , 2 , 0 , 6 , 7 , 0 , 4 } ; int index= 0 ; int arr1[]= new int [arr. length ] ; for ( int i= 0 ; i<arr. length ; i++){ if (arr[i]!= 0 ){ arr1[index] =arr[i] ; index++ ; } } for ( int i= 0 ; i<arr1. length ; i++){ System. out .print(arr1[i]) ; } } }

find peak element

  public class find_peak_element { public static void main (String[] args) { int [] arr ={ 4 , 78 , 1 , 90 , 232 , 34 , 66 , 453 , 333 , 321 , 786 , 999 , 923 } ; for ( int i= 1 ; i<arr. length ; i++){ if (arr[i]>arr[i- 1 ] && arr[i]>arr[i+ 1 ]){ System. out .println(arr[i]) ; } } } }

Merge 2 sorted arrays

  import java.util.Map ; import java.util.TreeMap ; public class merge_two_sorted_arrays { public static void main (String[] args) { int arr[] = { 1 , 3 , 6 , 8 } ; int arr1[] = { 2 , 4 , 5 , 7 } ; Map<Integer , Boolean> map = new TreeMap<Integer , Boolean>() ; for ( int i= 0 ; i<arr. length ; i++){ map.put(arr[i] ,true ) ; } for ( int i= 0 ; i<arr1. length ; i++){ map.put(arr1[i] ,true ) ; } map.forEach((key , value)->{ System. out .print(key) ; }) ; } }

Rotate the array with number

  import org.w3c.dom.ls.LSOutput ; public class rotate_integer_array { public static void main (String[] args) { int arr[] = { 3 , 4 , 1 , 6 , 9 , 8 } ; int [] arr1 ; arr1 = new int [arr. length ] ; int rot = 2 , count= 0 ; for ( int i= 0 ; i<=arr. length - 1 ; i++){ if (i<arr. length -rot){ arr1[i]=arr[i+rot] ; } else { arr1[i]=arr[count] ; count++ ; } } for ( int i= 0 ; i<arr1. length ; i++){ System. out .println(arr1[i]) ; } } }