- package sort_Map_byValue;
- import java.util.*;
- //Program to sort Map value
- //Map--->copy entry to List--->sort List using comparator-->copy to new Map-->display
- public class SortMapbyValue
- {
- public static void main(String[] args)
- {
- //Map create
- Map <String,Integer> map = new HashMap<>();
- map.put("A", 65);
- map.put("B", 60);
- map.put("C", 75);
- map.put("D", 97);
- map.put("E", 90);
- map.put("F", 85);
- map.put("G", 81);
- map.put("H", 75);
- //copy to List
- //create linked List & pass entryset--> as it maintains the insertion order)
- List<Map.Entry<String,Integer>> list = new LinkedList<>(map.entrySet());
- //Sort List
- //MyComparator mc = new MyComparator();
- Collections.sort(list, new MyComparator());
- //copy the sorted to new LinkedHashMap (temp)
- Map<String,Integer> sortedMap = new LinkedHashMap<>();
- for(Map.Entry<String, Integer> entry : list)
- {
- sortedMap.put(entry.getKey(), entry.getValue());
- }
- //Dispaly the Sorted Map (Soerted According to Value)
- for(Map.Entry<String,Integer> entry : sortedMap.entrySet())
- {
- System.out.println(entry.getKey() +" : "+entry.getValue());
- }
- }
- }
- =================================================
- package sort_Map_byValue;
- import java.util.Comparator;
- import java.util.Map;
- public class MyComparator implements Comparator<Map.Entry<String, Integer>>
- {
- @Override
- public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2)
- {
- return (o1.getValue()).compareTo(o2.getValue());
- }
- }
- ==================================================
Java SE Guide,Java Tutorial,amit,amit manjhi,java, spring, sql,plsql,pl sql,webservices,oracle,java tutorial, interview questions,interview coding,java2080,java 20:80,manjhi,2080,amit manjhi 2080,amit manjhi 2080 blogger, amitin2019, manjhi blogger,java interview questions, java blog,amit manjhi software engineer,amit manjhi,
Thursday, February 7, 2019
Sort Map According to its Value (Used Comparator ,List & LinkedHashMap)
Sort Map by Values
package test;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class SortMapbyValues
{
public static boolean ASC = true;
public static boolean DESC = false;
public static void main(String[] args)
{
Map<String, Integer> unsortMap = new HashMap<>();
unsortMap.put("B", 55);
unsortMap.put("A", 80);
unsortMap.put("D", 20);
unsortMap.put("C", 70);
System.out.println("Before sorting......");
printMap(unsortMap);
System.out.println("After sorting ascending order......");
Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
printMap(sortedMapAsc);
System.out.println("After sorting descindeng order......");
Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
printMap(sortedMapDesc);
}
private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
{
List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());
// Sorting the list based on values
Collections.sort(list, new Comparator<Entry<String, Integer>>()
{
public int compare(Entry<String, Integer> o1,
Entry<String, Integer> o2)
{
if (order)
{
return o1.getValue().compareTo(o2.getValue());
}
else
{
return o2.getValue().compareTo(o1.getValue());
}
}
});
// Maintaining insertion order with the help of LinkedList
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : list)
{
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
public static void printMap(Map<String, Integer> map)
{
for (Entry<String, Integer> entry : map.entrySet())
{
System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
}
}
}
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class SortMapbyValues
{
public static boolean ASC = true;
public static boolean DESC = false;
public static void main(String[] args)
{
Map<String, Integer> unsortMap = new HashMap<>();
unsortMap.put("B", 55);
unsortMap.put("A", 80);
unsortMap.put("D", 20);
unsortMap.put("C", 70);
System.out.println("Before sorting......");
printMap(unsortMap);
System.out.println("After sorting ascending order......");
Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
printMap(sortedMapAsc);
System.out.println("After sorting descindeng order......");
Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
printMap(sortedMapDesc);
}
private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
{
List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());
// Sorting the list based on values
Collections.sort(list, new Comparator<Entry<String, Integer>>()
{
public int compare(Entry<String, Integer> o1,
Entry<String, Integer> o2)
{
if (order)
{
return o1.getValue().compareTo(o2.getValue());
}
else
{
return o2.getValue().compareTo(o1.getValue());
}
}
});
// Maintaining insertion order with the help of LinkedList
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : list)
{
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
public static void printMap(Map<String, Integer> map)
{
for (Entry<String, Integer> entry : map.entrySet())
{
System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
}
}
}
Sort Map using comparator
package test;
import java.util.*;
public class SortMap_TreeMap
{
public static void main(String[] args)
{
Map <String,String> unsortedmap = new HashMap<>();
unsortedmap.put("one", "one");
unsortedmap.put("tree", "tree");
unsortedmap.put("mount", "mount");
unsortedmap.put("bird", "bird");
unsortedmap.put("house", "house");
System.out.println("***************Unsorted Map**************");
printmap(unsortedmap);
System.out.println("************After sorting Map*************");
Map<String, String> sortedMap = sortMap(unsortedmap);
printmap(sortedMap);
}
private static Map<String, String> sortMap(Map<String, String> unsortedmap)
{
// copy unsortedmap to TreeMap
TreeMap <String,String> tm = new TreeMap<>(new SortMapComparator());
for(Map.Entry<String,String> entry : unsortedmap.entrySet())
{
tm.put(entry.getKey(), entry.getValue());
}
return tm;
}
private static void printmap(Map<String, String> unsortedmap)
{
for(Map.Entry<String,String> entry : unsortedmap.entrySet())
{
System.out.println(entry.getKey()+" : "+entry.getValue());
}
}
}
import java.util.*;
public class SortMap_TreeMap
{
public static void main(String[] args)
{
Map <String,String> unsortedmap = new HashMap<>();
unsortedmap.put("one", "one");
unsortedmap.put("tree", "tree");
unsortedmap.put("mount", "mount");
unsortedmap.put("bird", "bird");
unsortedmap.put("house", "house");
System.out.println("***************Unsorted Map**************");
printmap(unsortedmap);
System.out.println("************After sorting Map*************");
Map<String, String> sortedMap = sortMap(unsortedmap);
printmap(sortedMap);
}
private static Map<String, String> sortMap(Map<String, String> unsortedmap)
{
// copy unsortedmap to TreeMap
TreeMap <String,String> tm = new TreeMap<>(new SortMapComparator());
for(Map.Entry<String,String> entry : unsortedmap.entrySet())
{
tm.put(entry.getKey(), entry.getValue());
}
return tm;
}
private static void printmap(Map<String, String> unsortedmap)
{
for(Map.Entry<String,String> entry : unsortedmap.entrySet())
{
System.out.println(entry.getKey()+" : "+entry.getValue());
}
}
}
=========================================
package test;
import java.util.Comparator;
public class SortMapComparator implements Comparator <String>
{
@Override
public int compare(String s1 , String s2)
{
return s1.compareTo(s2);
}
}
Wednesday, February 6, 2019
Sort Map by Key
package interview;
import java.util.*;
//Sort HashMap according to key
//Map -->Map(to keeep sorted items)---->TreeMap---(default comparable)-->Sorted
public class SortHashMap_1 {
public static void main(String[] args)
{
Map <String, String> map = new HashMap<>();
map.put("orange", "orange");
map.put("guava", "guava");
map.put("mango", "mango");
map.put("pineapple", "pineapple");
map.put("banana", "banana");
map.put("grapes", "grapes");
System.out.println(map);
//TreeMap is a class which follows some sorting order for elements
Map <String,String> map2 = new TreeMap(map);
//Now display
System.out.println("*********************Sorted *************************");
for(Map.Entry<String,String> entry : map2.entrySet())
{
System.out.println(entry.getKey() +" : "+entry.getValue());
}
}
}
import java.util.*;
//Sort HashMap according to key
//Map -->Map(to keeep sorted items)---->TreeMap---(default comparable)-->Sorted
public class SortHashMap_1 {
public static void main(String[] args)
{
Map <String, String> map = new HashMap<>();
map.put("orange", "orange");
map.put("guava", "guava");
map.put("mango", "mango");
map.put("pineapple", "pineapple");
map.put("banana", "banana");
map.put("grapes", "grapes");
System.out.println(map);
//TreeMap is a class which follows some sorting order for elements
Map <String,String> map2 = new TreeMap(map);
//Now display
System.out.println("*********************Sorted *************************");
for(Map.Entry<String,String> entry : map2.entrySet())
{
System.out.println(entry.getKey() +" : "+entry.getValue());
}
}
}
Sort Map using Key
package test;
import java.util.Map;
import java.util.TreeMap;
public class Sorting_TreeMap_DNSO {
public static void main(String[] args)
{
Map <String,String> map = new TreeMap<>(); //Sorting : Default Natural(Keys)
map.put("orange", "orange");
map.put("guava", "guava");
map.put("mango", "mango");
map.put("pineapple", "pineapple");
map.put("banana", "banana");
System.out.println(map);
}
}
import java.util.Map;
import java.util.TreeMap;
public class Sorting_TreeMap_DNSO {
public static void main(String[] args)
{
Map <String,String> map = new TreeMap<>(); //Sorting : Default Natural(Keys)
map.put("orange", "orange");
map.put("guava", "guava");
map.put("mango", "mango");
map.put("pineapple", "pineapple");
map.put("banana", "banana");
System.out.println(map);
}
}
Program to Reverse an array
Solution 1 - Revere array in Place (not recommended)
package interview;
import java.util.Arrays;
import java.util.List;
public class Reverse_Array {
public static void main(String[] args)
{
int[] arr = {1,2,3,4,5,6,7,8,9,10};
System.out.println("Before : "+Arrays.toString(arr));
/*List<int[]> l = Arrays.asList(arr);
System.out.println(l.toArray());*/
for(int i =0 , j = arr.length-1; i<j; i++,j--)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
System.out.println("After : "+Arrays.toString(arr));
}
}
Solution 2 - Revere array in Place (for interview)
package phase_one;
import java.util.Arrays;
public class ReverseArray_Using_ForLoop
{
public static void main(String[] args)
{
int[] arr = new int[] {7,84,3,9,11,6};
System.out.println("Before: "+Arrays.toString(arr));
for(int i= 0;i<arr.length/2;i++)
{
int temp = arr[i];
arr[i] = arr[arr.length-i-1];
arr[arr.length-i-1] = temp;
}
System.out.println("After: "+Arrays.toString(arr));
}
}
Solution 3 - Revere array Using Collections
package phase_one;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ReverseArray_Using_ArrayList {
public static void main(String[] args)
{
String[] arr = {"apple", "tree", "play"};
System.out.println("before: " + Arrays.toString(arr) );
List<String> listOfProducts = Arrays.asList(arr);
Collections.reverse(listOfProducts);
String[] reversed = listOfProducts.toArray(arr);
System.out.println("after: " + Arrays.toString(reversed) );
System.out.println("**************************************");
Integer[] arr2 = new Integer[] {1,2,3,4,5};
// List<Integer> list = Arrays.asList(arr2);
System.out.println(Arrays.toString(arr2));
List<Integer> li = Arrays.asList(arr2); //--array to List
Collections.reverse(li); // reverse List
Integer[] rev = li.toArray(arr2);
System.out.println(Arrays.toString(rev));
}
}
Reverse_String_Without_API
package interview;
public class Reverse_String_Without_API {
public static void main(String[] args)
{
String str = "Gopalpur";
String reverse = "";
char[] ch = str.toCharArray();
for(int i = ch.length-1; i>=0;i--)
{
reverse = reverse +ch[i];
}
System.out.println(reverse);
}
}
public class Reverse_String_Without_API {
public static void main(String[] args)
{
String str = "Gopalpur";
String reverse = "";
char[] ch = str.toCharArray();
for(int i = ch.length-1; i>=0;i--)
{
reverse = reverse +ch[i];
}
System.out.println(reverse);
}
}
Swapping_Two_Numbers_without_Temp_Variable
package interview;
public class Swapping_Two_Numbers_without_Temp_Variable
{
public static void main(String[] args)
{
int num1 = 54;
int num2 = 45;
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("num1: "+num1);
System.out.println("num2: "+num2);
}
}
public class Swapping_Two_Numbers_without_Temp_Variable
{
public static void main(String[] args)
{
int num1 = 54;
int num2 = 45;
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("num1: "+num1);
System.out.println("num2: "+num2);
}
}
RemoveWhiteSpace_PrintNoLasComma
public class RemoveWhiteSpace_PrintNoLasComma{
public static void main(String[] args)
{
String str = "Hello wor ld";
str = str.replaceAll("\\s","");
//System.out.println(str);
char[] ch = str.toCharArray();
for(int i =0;i<ch.length;i++)
{
System.out.print((i == 0 ? ch[i] :","+ch[i] ));
}
}
}
public static void main(String[] args)
{
String str = "Hello wor ld";
str = str.replaceAll("\\s","");
//System.out.println(str);
char[] ch = str.toCharArray();
for(int i =0;i<ch.length;i++)
{
System.out.print((i == 0 ? ch[i] :","+ch[i] ));
}
}
}
Tuesday, February 5, 2019
String_Links
- Duplicate Strings
- Permutation
- Program to count vowels, consonant, digits and special characters in string
- Count Words,char,duplicate Words from File
- Anagram String
- Anagram String 2
- Anagram String 3
- Check_If_String_Contains_only_Digit
- Count_Character_WithoutLoop
- Count Words
- Duplicate Char
- Duplic_Char
- Duplicate Char Display
- Duplicate Strings
- Fibonacci
- First Non Repeated Character
- Palindrom_Num
- Reverse_Each_Word
- RemoveSpace
- ReverseEachSring_StringBuffer
- ReverseEachString_CharArray
- RemoveWhiteSpace_PrintNoLasComma
- Swapping_Two_Numbers_without_Temp_Variable
- Reverse_String_Without_API
- Program to Reverse an array
DuplicateStrings
package interview;
import java.util.*;
public class DuplicateStrings
{
//String-->String.split()--->String[]--->Uppercase--->Hashmap
public static void main(String[] args)
{
String str = "This is what is this world in world 45 67 45";
String[] str2 = str.split(" ");
String[] str3 = toUpperString(str2);
show(str3);
Map<String,Integer> map = new HashMap<>();
for(String s : str3)
{
if(map.containsKey(s))
{
map.put(s,map.get(s)+1);
}
else
{
map.put(s, 1);
}
}
//*****************************
for(Map.Entry<String,Integer> entry : map.entrySet())
{
if(entry.getValue()>1)
{
System.out.println(entry.getKey()+" --->"+entry.getValue());
}
}
}
private static void show(String[] str3)
{
for(String s : str3)
System.out.print(s+" ");
System.out.println("");
}
private static String[] toUpperString(String[] str2)
{
for(int i =0;i<str2.length;i++)
{
str2[i] = str2[i].toUpperCase();
}
return str2;
}
}
import java.util.*;
public class DuplicateStrings
{
//String-->String.split()--->String[]--->Uppercase--->Hashmap
public static void main(String[] args)
{
String str = "This is what is this world in world 45 67 45";
String[] str2 = str.split(" ");
String[] str3 = toUpperString(str2);
show(str3);
Map<String,Integer> map = new HashMap<>();
for(String s : str3)
{
if(map.containsKey(s))
{
map.put(s,map.get(s)+1);
}
else
{
map.put(s, 1);
}
}
//*****************************
for(Map.Entry<String,Integer> entry : map.entrySet())
{
if(entry.getValue()>1)
{
System.out.println(entry.getKey()+" --->"+entry.getValue());
}
}
}
private static void show(String[] str3)
{
for(String s : str3)
System.out.print(s+" ");
System.out.println("");
}
private static String[] toUpperString(String[] str2)
{
for(int i =0;i<str2.length;i++)
{
str2[i] = str2[i].toUpperCase();
}
return str2;
}
}
Mixed String
Java String toCharArray()
-------------------------
The java string toCharArray() method converts this string into character array. It returns a newly created character array, its length is similar to this string and its contents are initialized with the characters of this string.
==========================================
Character.toUpperCase(char ch)
----
char a = 'a';
char upperCase = Character.toUpperCase(a);
===========================================
Character.isLetter('c')
Character.isLowerCase('c')
public class Test {
public static void main(String args[]) {
System.out.println(Character.isLetter('c'));
System.out.println(Character.isLetter('5'));
System.out.println(Character.isLowerCase('c'));
System.out.println(Character.isLowerCase('C'));
}
}
output:-
true
false
true
false
============================================
if(Character.isLetter(charmessage[counter]) &&
Character.isLowerCase(charmessage[counter]))
{
charmessage[counter] = Character.toUpperCase(charmessage[counter]);
}
================
String str = "This is what is this world in world";
String[] strarray = str.split(" ");
=============================================
Arrays.sort(ch1);
Arrays.sort(ch2);
if(Arrays.equals(ch1,ch2))
=============================================
public StringBuffer deleteCharAt(int index)
----
StringBuffer buff = new StringBuffer("Java lang package");
System.out.println("buffer = " + buff);
// deleting character from index 4 to index 9
buff.delete(4, 9);
System.out.println("After deletion = " + buff);
buff = new StringBuffer("xxxx);
System.out.println("buffer = " + buff);
// deleting character at index 2
buff.deleteCharAt(2);
System.out.println("After deletion = " + buff);
==============================================
// create StringBuffer object
StringBuffer sb = new StringBuffer();
// 1. append some string values
sb.append("Google is top search-engine. ");
// 2. again, append some more string values
sb.append("To get latest topics on Core Java.");
// 3. third time, append String-3 and
// add newline '\n'
sb.append("\nAnd it can search contents in real-time.");
// convert StringBuffer to String using toString() method
String str = sb.toString();
===============================================
--Covert char to String
------------------------
char a ='t';
String s = ""+a;
String ss = Character.toString(a);
String sss = String.valueOf(a);
================================================
copyOf()
--------
Syntax:
copyOf(int[] original, int newLength)
----eg.
public static void main(String args[])
{
// initializing an array original
int[] org = new int[] {1, 2 ,3};
System.out.println("Original Array");
for (int i = 0; i < org.length; i++)
System.out.print(org[i] + " ");
// copying array org to copy
int[] copy = Arrays.copyOf(org, 5);
// Changing some elements of copy
copy[3] = 11;
copy[4] = 55;
System.out.println("\nNew array copy after modifications:");
for (int i = 0; i < copy.length; i++)
System.out.print(copy[i] + " ");
}
-----------------------------------------------------------------------------------------
--System.arraycopy()
--
Syntax :
public static void
arraycopy(Object source_arr, int sourcePos,Object dest_arr, int destPos, int len)
---eg.
public static void main(String[] args)
{
int s[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int d[] = { 15, 25, 35, 45, 55, 65, 75, 85, 95, 105};
int source_arr[], sourcePos, dest_arr[], destPos, len;
source_arr = s;
sourcePos = 3;
dest_arr = d;
destPos = 5;
len = 4;
// Print elements of source
System.out.print("source_array : ");
for (int i = 0; i < s.length; i++)
System.out.print(s[i] + " ");
System.out.println("");
System.out.println("sourcePos : " + sourcePos);
// Print elements of source
System.out.print("dest_array : ");
for (int i = 0; i < d.length; i++)
System.out.print(d[i] + " ");
System.out.println("");
System.out.println("destPos : " + destPos);
System.out.println("len : " + len);
// Use of arraycopy() method
System.arraycopy(source_arr, sourcePos, dest_arr,
destPos, len);
// Print elements of destination after
System.out.print("final dest_array : ");
for (int i = 0; i < d.length; i++)
System.out.print(d[i] + " ");
}
-----------------------------------------------------------------------------------------
Object[] obj = list.toArray();//ArrayList to Array
for copying arraylist to array
---------------------------
---------------------------
1.List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia)); //copy
2.List<Integer> list2 = Arrays.asList(ia);
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating Arrays of String type
String a[] = new String[] { "A", "B", "C", "D" };
// getting the list view of Array
List<String> list = Arrays.asList(a);
// printing the list
System.out.println("The list is: " + list);
}
catch (NullPointerException e) {
System.out.println("Exception thrown : " + e);
}
}
}
Output:
The list is: [A, B, C, D]
----------------------------------
=========================================================
----------------------------------string to char[]
String s1="hello";
char[] ch1 = s1.toCharArray();
----------------------------------to sort char []
Arrays.sort(ch1);
----------------------------------
int value=30;
String s1=String.valueOf(value);
System.out.println(s1+10);
//concatenating string with 10
//o/p :- 3010
----------------------------------
String s1 = "java";
String s2 = "ajav";
StringBuffer sb = new StringBuffer(s2);
int index = sb.indexOf(String.valueOf(c));
sb.deleteCharAt(index);
-------------------------------------
String s2 ="avaj";
StringBuffer sb = new StringBuffer(s2);
int index = sb.indexOf(String.valueOf(c)); --or
int index = sb.indexOf(Character.toString(c));
sb.deleteCharAt(index);
---------------------------------------
----------- char array to a string in Java?
class CharArrayToString
{
public static void main(String args[])
{
// Method 1: Using String object
char[] ch = {'g', 'o', 'o', 'd', ' ', 'm', 'o', 'r', 'n', 'i', 'n', 'g'};
String str = new String(ch);
System.out.println(str);
// Method 2: Using valueOf method
String str2 = String.valueOf(ch);
System.out.println(str2);
}
}
---------------------------------------
=================================================
package comparator.Emp;
//When we are not allowed to change Class Employee code (i.e we can't implement Comparable)
//We use comparator Interface.
public class Employee
{
int empid;
String name;
int deptid;
public Employee(int empid, String name, int deptid)
{
super();
this.empid = empid;
this.name = name;
this.deptid = deptid;
}
/*@Override
public String toString() {
return "Empid=" + empid + ", Name=" + name + ", Deptid=" + deptid;
}*/
}
==========================================
package comparator.Emp;
import java.util.*;
//Sort the Employeee Class using empid -- Use Comparator
public class Emp_Runner {
public static void main(String[] args)
{
Employee emp1 = new Employee(111,"Amit",549);
Employee emp2 = new Employee(674,"Dinesh",549);
Employee emp3 = new Employee(352,"Manohar",667);
Employee emp4 = new Employee(642,"Dilip",889);
Employee emp5 = new Employee(133,"Govind",667);
List list = new ArrayList();
list.add(emp1);
list.add(emp2);
list.add(emp3);
list.add(emp4);
list.add(emp5);
Comparator comp = new Emp_Comp(); //Comparator is Interface so we can't instanciate it.
Collections.sort(list,new Emp_Comp()); //call to compare() .... from here
Iterator itr = list.iterator();
while(itr.hasNext())
{
Employee emp = (Employee) itr.next();
System.out.println("Empid=" + emp.empid + ", Name=" + emp.name + ", Deptid=" + emp.deptid);
}
}
}
==========================================
package comparator.Emp;
import java.util.Comparator;
public class Emp_Comp implements Comparator<Employee>
{
@Override
public int compare(Employee e1, Employee e2)
{
if(e1.empid > e2.empid)
{
return 1;
}
else return
-1;
}
}
============================================
============================================
-------------------------
The java string toCharArray() method converts this string into character array. It returns a newly created character array, its length is similar to this string and its contents are initialized with the characters of this string.
==========================================
Character.toUpperCase(char ch)
----
char a = 'a';
char upperCase = Character.toUpperCase(a);
===========================================
Character.isLetter('c')
Character.isLowerCase('c')
public class Test {
public static void main(String args[]) {
System.out.println(Character.isLetter('c'));
System.out.println(Character.isLetter('5'));
System.out.println(Character.isLowerCase('c'));
System.out.println(Character.isLowerCase('C'));
}
}
output:-
true
false
true
false
============================================
if(Character.isLetter(charmessage[counter]) &&
Character.isLowerCase(charmessage[counter]))
{
charmessage[counter] = Character.toUpperCase(charmessage[counter]);
}
================
String str = "This is what is this world in world";
String[] strarray = str.split(" ");
=============================================
Arrays.sort(ch1);
Arrays.sort(ch2);
if(Arrays.equals(ch1,ch2))
=============================================
public StringBuffer deleteCharAt(int index)
----
StringBuffer buff = new StringBuffer("Java lang package");
System.out.println("buffer = " + buff);
// deleting character from index 4 to index 9
buff.delete(4, 9);
System.out.println("After deletion = " + buff);
buff = new StringBuffer("xxxx);
System.out.println("buffer = " + buff);
// deleting character at index 2
buff.deleteCharAt(2);
System.out.println("After deletion = " + buff);
==============================================
// create StringBuffer object
StringBuffer sb = new StringBuffer();
// 1. append some string values
sb.append("Google is top search-engine. ");
// 2. again, append some more string values
sb.append("To get latest topics on Core Java.");
// 3. third time, append String-3 and
// add newline '\n'
sb.append("\nAnd it can search contents in real-time.");
// convert StringBuffer to String using toString() method
String str = sb.toString();
===============================================
--Covert char to String
------------------------
char a ='t';
String s = ""+a;
String ss = Character.toString(a);
String sss = String.valueOf(a);
================================================
copyOf()
--------
Syntax:
copyOf(int[] original, int newLength)
----eg.
public static void main(String args[])
{
// initializing an array original
int[] org = new int[] {1, 2 ,3};
System.out.println("Original Array");
for (int i = 0; i < org.length; i++)
System.out.print(org[i] + " ");
// copying array org to copy
int[] copy = Arrays.copyOf(org, 5);
// Changing some elements of copy
copy[3] = 11;
copy[4] = 55;
System.out.println("\nNew array copy after modifications:");
for (int i = 0; i < copy.length; i++)
System.out.print(copy[i] + " ");
}
-----------------------------------------------------------------------------------------
--System.arraycopy()
--
Syntax :
public static void
arraycopy(Object source_arr, int sourcePos,Object dest_arr, int destPos, int len)
---eg.
public static void main(String[] args)
{
int s[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int d[] = { 15, 25, 35, 45, 55, 65, 75, 85, 95, 105};
int source_arr[], sourcePos, dest_arr[], destPos, len;
source_arr = s;
sourcePos = 3;
dest_arr = d;
destPos = 5;
len = 4;
// Print elements of source
System.out.print("source_array : ");
for (int i = 0; i < s.length; i++)
System.out.print(s[i] + " ");
System.out.println("");
System.out.println("sourcePos : " + sourcePos);
// Print elements of source
System.out.print("dest_array : ");
for (int i = 0; i < d.length; i++)
System.out.print(d[i] + " ");
System.out.println("");
System.out.println("destPos : " + destPos);
System.out.println("len : " + len);
// Use of arraycopy() method
System.arraycopy(source_arr, sourcePos, dest_arr,
destPos, len);
// Print elements of destination after
System.out.print("final dest_array : ");
for (int i = 0; i < d.length; i++)
System.out.print(d[i] + " ");
}
-----------------------------------------------------------------------------------------
Object[] obj = list.toArray();//ArrayList to Array
for copying arraylist to array
---------------------------
---------------------------
1.List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia)); //copy
2.List<Integer> list2 = Arrays.asList(ia);
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating Arrays of String type
String a[] = new String[] { "A", "B", "C", "D" };
// getting the list view of Array
List<String> list = Arrays.asList(a);
// printing the list
System.out.println("The list is: " + list);
}
catch (NullPointerException e) {
System.out.println("Exception thrown : " + e);
}
}
}
Output:
The list is: [A, B, C, D]
----------------------------------
=========================================================
----------------------------------string to char[]
String s1="hello";
char[] ch1 = s1.toCharArray();
----------------------------------to sort char []
Arrays.sort(ch1);
----------------------------------
int value=30;
String s1=String.valueOf(value);
System.out.println(s1+10);
//concatenating string with 10
//o/p :- 3010
----------------------------------
String s1 = "java";
String s2 = "ajav";
StringBuffer sb = new StringBuffer(s2);
int index = sb.indexOf(String.valueOf(c));
sb.deleteCharAt(index);
-------------------------------------
String s2 ="avaj";
StringBuffer sb = new StringBuffer(s2);
int index = sb.indexOf(String.valueOf(c)); --or
int index = sb.indexOf(Character.toString(c));
sb.deleteCharAt(index);
---------------------------------------
----------- char array to a string in Java?
class CharArrayToString
{
public static void main(String args[])
{
// Method 1: Using String object
char[] ch = {'g', 'o', 'o', 'd', ' ', 'm', 'o', 'r', 'n', 'i', 'n', 'g'};
String str = new String(ch);
System.out.println(str);
// Method 2: Using valueOf method
String str2 = String.valueOf(ch);
System.out.println(str2);
}
}
---------------------------------------
=================================================
package comparator.Emp;
//When we are not allowed to change Class Employee code (i.e we can't implement Comparable)
//We use comparator Interface.
public class Employee
{
int empid;
String name;
int deptid;
public Employee(int empid, String name, int deptid)
{
super();
this.empid = empid;
this.name = name;
this.deptid = deptid;
}
/*@Override
public String toString() {
return "Empid=" + empid + ", Name=" + name + ", Deptid=" + deptid;
}*/
}
==========================================
package comparator.Emp;
import java.util.*;
//Sort the Employeee Class using empid -- Use Comparator
public class Emp_Runner {
public static void main(String[] args)
{
Employee emp1 = new Employee(111,"Amit",549);
Employee emp2 = new Employee(674,"Dinesh",549);
Employee emp3 = new Employee(352,"Manohar",667);
Employee emp4 = new Employee(642,"Dilip",889);
Employee emp5 = new Employee(133,"Govind",667);
List list = new ArrayList();
list.add(emp1);
list.add(emp2);
list.add(emp3);
list.add(emp4);
list.add(emp5);
Comparator comp = new Emp_Comp(); //Comparator is Interface so we can't instanciate it.
Collections.sort(list,new Emp_Comp()); //call to compare() .... from here
Iterator itr = list.iterator();
while(itr.hasNext())
{
Employee emp = (Employee) itr.next();
System.out.println("Empid=" + emp.empid + ", Name=" + emp.name + ", Deptid=" + emp.deptid);
}
}
}
==========================================
package comparator.Emp;
import java.util.Comparator;
public class Emp_Comp implements Comparator<Employee>
{
@Override
public int compare(Employee e1, Employee e2)
{
if(e1.empid > e2.empid)
{
return 1;
}
else return
-1;
}
}
============================================
============================================
Permutation
package interview;
public class Permuter
{
public static void main(String[] args)
{
String str = "ABC";
permute(str,0,str.length()-1);
}
private static void permute(String str, int start, int end)
{
if(start==end)
{
System.out.println(str);
return;
}
for(int i = start;i<=end;i++)
{
str = swap(str,start,i);
permute(str,start+1,end);
str = swap(str,start,i);
}
}
private static String swap(String str, int start, int i)
{
char[] ch = str.toCharArray();
char temp = ch[start];
ch[start]= ch[i];
ch[i] = temp;
//String str2 = ch.toString();
return String.valueOf(ch);
}
}
public class Permuter
{
public static void main(String[] args)
{
String str = "ABC";
permute(str,0,str.length()-1);
}
private static void permute(String str, int start, int end)
{
if(start==end)
{
System.out.println(str);
return;
}
for(int i = start;i<=end;i++)
{
str = swap(str,start,i);
permute(str,start+1,end);
str = swap(str,start,i);
}
}
private static String swap(String str, int start, int i)
{
char[] ch = str.toCharArray();
char temp = ch[start];
ch[start]= ch[i];
ch[i] = temp;
//String str2 = ch.toString();
return String.valueOf(ch);
}
}
Program to count vowels, consonant, digits and special characters in string
package test;
import java.util.Scanner;
public class Count_vowel_cons_digit_symbol
{
public static void main(String[] args)
{
System.out.println("Enter string");
Scanner kb = new Scanner(System.in);
String string = kb.nextLine();
displaycount(string);
}
private static void displaycount(String s)
{
int vowel =0;
int consonent =0;
int whitespace = 0;
int digit = 0;
int symbol = 0;
String string = s.toLowerCase();
System.out.println(string);
for(int i=0;i<string.length();i++)
{
char ch = string.charAt(i);
if((ch>='a' && ch<='z')||(ch>='A' && ch<='Z'))
{
switch(ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
vowel++;
break;
default:
consonent++;
}
}
else if(ch>='0' && ch<='9')
digit++;
else if(Character.isWhitespace(ch))
whitespace++;
else
{
symbol++;
}
}
System.out.println("Vowels: "+vowel);
System.out.println("consonent: "+consonent);
System.out.println("whitespace: "+whitespace);
System.out.println("digit: "+digit);
System.out.println("symbol: "+symbol);
}
}
import java.util.Scanner;
public class Count_vowel_cons_digit_symbol
{
public static void main(String[] args)
{
System.out.println("Enter string");
Scanner kb = new Scanner(System.in);
String string = kb.nextLine();
displaycount(string);
}
private static void displaycount(String s)
{
int vowel =0;
int consonent =0;
int whitespace = 0;
int digit = 0;
int symbol = 0;
String string = s.toLowerCase();
System.out.println(string);
for(int i=0;i<string.length();i++)
{
char ch = string.charAt(i);
if((ch>='a' && ch<='z')||(ch>='A' && ch<='Z'))
{
switch(ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
vowel++;
break;
default:
consonent++;
}
}
else if(ch>='0' && ch<='9')
digit++;
else if(Character.isWhitespace(ch))
whitespace++;
else
{
symbol++;
}
}
System.out.println("Vowels: "+vowel);
System.out.println("consonent: "+consonent);
System.out.println("whitespace: "+whitespace);
System.out.println("digit: "+digit);
System.out.println("symbol: "+symbol);
}
}
Monday, February 4, 2019
Count Words,char,duplicate Words from File
package test;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/*
No. of Words:
No. of characters:
List to duplicate Words:
D:\work\Java Work Space\files\amit.txt
*/
public class Count_Duplicate_Words_From_File
{
public static void main(String[] args) throws IOException, FileNotFoundException
{
BufferedReader br = new BufferedReader(new FileReader("D:\\work\\Java Work Space\\files\\amit.txt"));
StringBuffer sb = new StringBuffer();
String s = br.readLine();
while(s!= null)
{
//sb = sb.append(s); //----->White ko hatna hetu
sb = sb.append(s.trim());
sb = sb.append(" ");
s = br.readLine();
}
br.close();
String[] words = sb.toString().split(" ");
wordCount(words);
charCount(words);
DupWords(words);
}
private static void DupWords(String[] words)
{
Map <String,Integer> map = new HashMap<>();
for(String s : words)
{
if(!map.containsKey(s))
{
map.put(s, 1);
}
else
{
map.put(s, map.get(s)+1);
}
}
System.out.println("List to duplicate Words:");
for(Map.Entry<String,Integer> entry : map.entrySet())
{
if(entry.getValue()>1)
System.out.println(entry.getKey()+" : "+entry.getValue());
}
}
private static void charCount(String[] words)
{
char[] ch;
int count = -1;
for (String s : words)
{
for(int i = 0;i<s.length();i++)
{
count++;
}
count++;
}
System.out.println("No. of characters: "+count);
}
private static void wordCount(String[] words)
{
System.out.println(Arrays.toString(words));
System.out.println("No of Words: "+words.length);
}
}
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/*
No. of Words:
No. of characters:
List to duplicate Words:
D:\work\Java Work Space\files\amit.txt
*/
public class Count_Duplicate_Words_From_File
{
public static void main(String[] args) throws IOException, FileNotFoundException
{
BufferedReader br = new BufferedReader(new FileReader("D:\\work\\Java Work Space\\files\\amit.txt"));
StringBuffer sb = new StringBuffer();
String s = br.readLine();
while(s!= null)
{
//sb = sb.append(s); //----->White ko hatna hetu
sb = sb.append(s.trim());
sb = sb.append(" ");
s = br.readLine();
}
br.close();
String[] words = sb.toString().split(" ");
wordCount(words);
charCount(words);
DupWords(words);
}
private static void DupWords(String[] words)
{
Map <String,Integer> map = new HashMap<>();
for(String s : words)
{
if(!map.containsKey(s))
{
map.put(s, 1);
}
else
{
map.put(s, map.get(s)+1);
}
}
System.out.println("List to duplicate Words:");
for(Map.Entry<String,Integer> entry : map.entrySet())
{
if(entry.getValue()>1)
System.out.println(entry.getKey()+" : "+entry.getValue());
}
}
private static void charCount(String[] words)
{
char[] ch;
int count = -1;
for (String s : words)
{
for(int i = 0;i<s.length();i++)
{
count++;
}
count++;
}
System.out.println("No. of characters: "+count);
}
private static void wordCount(String[] words)
{
System.out.println(Arrays.toString(words));
System.out.println("No of Words: "+words.length);
}
}
FileWriter_1
package fileHandling;
import java.io.File;
import java.io.*;
public class FileWriter_1 {
public static void main(String[] args) throws IOException
{
File f = new File("D:\\work\\Java Work Space\\files\\amit.txt");
f.createNewFile();
System.out.println(f.exists());
FileWriter fw = new FileWriter(f); //it overrites everytime
fw.write(97); //--->a
fw.write('\n');
fw.write("Book\n");
fw.write('\n'+"on the Table");
fw.flush();
fw.close();
}
}
import java.io.File;
import java.io.*;
public class FileWriter_1 {
public static void main(String[] args) throws IOException
{
File f = new File("D:\\work\\Java Work Space\\files\\amit.txt");
f.createNewFile();
System.out.println(f.exists());
FileWriter fw = new FileWriter(f); //it overrites everytime
fw.write(97); //--->a
fw.write('\n');
fw.write("Book\n");
fw.write('\n'+"on the Table");
fw.flush();
fw.close();
}
}
FileReaderDemo
package fileHandling;
import java.io.*;
import java.util.Arrays;
public class FileReaderDemo
{
public static void main(String[] args) throws IOException,FileNotFoundException
{
FileReader f = new FileReader("D:\\work\\Java Work Space\\files\\demo.txt");
BufferedReader br = new BufferedReader(f);
String s = br.readLine();
StringBuffer sb = new StringBuffer();
while(s!=null)
{
sb = sb.append(s);
sb = sb.append(" ");
s = br.readLine();
}
br.close();
String[] words = sb.toString().split(" ");
System.out.println(words.length);
System.out.println(Arrays.toString(words));
}
}
import java.io.*;
import java.util.Arrays;
public class FileReaderDemo
{
public static void main(String[] args) throws IOException,FileNotFoundException
{
FileReader f = new FileReader("D:\\work\\Java Work Space\\files\\demo.txt");
BufferedReader br = new BufferedReader(f);
String s = br.readLine();
StringBuffer sb = new StringBuffer();
while(s!=null)
{
sb = sb.append(s);
sb = sb.append(" ");
s = br.readLine();
}
br.close();
String[] words = sb.toString().split(" ");
System.out.println(words.length);
System.out.println(Arrays.toString(words));
}
}
FileReader_1
package fileHandling;
import java.io.*;
public class FileReader_1 {
public static void main(String[] args) throws IOException
{
File f = new File("D:\\work\\Java Work Space\\files\\demo.txt");
f.createNewFile();
FileWriter fw = new FileWriter(f);
fw.write("Hero Honda started its operations");
fw.flush();
fw.close();
FileReader fr = new FileReader("D:\\work\\Java Work Space\\files\\demo.txt");
int i = fr.read();
while(i != -1)
{
System.out.print((char)i);
i = fr.read();
}
}
}
import java.io.*;
public class FileReader_1 {
public static void main(String[] args) throws IOException
{
File f = new File("D:\\work\\Java Work Space\\files\\demo.txt");
f.createNewFile();
FileWriter fw = new FileWriter(f);
fw.write("Hero Honda started its operations");
fw.flush();
fw.close();
FileReader fr = new FileReader("D:\\work\\Java Work Space\\files\\demo.txt");
int i = fr.read();
while(i != -1)
{
System.out.print((char)i);
i = fr.read();
}
}
}
File_Create
package fileHandling;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
public class File_Create {
public static void main(String[] args) throws IOException
{
//************************count files text lenght***************************
File f = new File("D:\\work\\Java Work Space\\files\\text1.txt");
long l = f.length();
System.out.println("text1 has "+l+" letters");
/* System.out.println(f.exists());
//f.createNewFile();
f.mkdir();
System.out.println(f.exists());*/
//************************count files******************************
File f2 = new File("D:\\work\\Java Work Space\\files");
String[] s2 = f2.list();
System.out.println(":List of files:");
System.out.print(Arrays.toString(s2));
/*for (String string : s2)
{
System.out.print(string+", ");
}*/
}
}
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
public class File_Create {
public static void main(String[] args) throws IOException
{
//************************count files text lenght***************************
File f = new File("D:\\work\\Java Work Space\\files\\text1.txt");
long l = f.length();
System.out.println("text1 has "+l+" letters");
/* System.out.println(f.exists());
//f.createNewFile();
f.mkdir();
System.out.println(f.exists());*/
//************************count files******************************
File f2 = new File("D:\\work\\Java Work Space\\files");
String[] s2 = f2.list();
System.out.println(":List of files:");
System.out.print(Arrays.toString(s2));
/*for (String string : s2)
{
System.out.print(string+", ");
}*/
}
}
Count_Words
package fileHandling;
import java.io.*;
public class Count_Words {
public static void main(String[] args) throws FileNotFoundException,IOException
{
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new FileReader("D:\\work\\Java Work Space\\files\\demo.txt"));
String s = br.readLine();
while(s!= null)
{
sb = sb.append(s);
//System.out.println(s);
s = br.readLine();
sb.append(" ");
}
String s2 = sb.toString();
System.out.println(s2.length());
String[] words = s2.toLowerCase().split(" ");
}
}
import java.io.*;
public class Count_Words {
public static void main(String[] args) throws FileNotFoundException,IOException
{
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new FileReader("D:\\work\\Java Work Space\\files\\demo.txt"));
String s = br.readLine();
while(s!= null)
{
sb = sb.append(s);
//System.out.println(s);
s = br.readLine();
sb.append(" ");
}
String s2 = sb.toString();
System.out.println(s2.length());
String[] words = s2.toLowerCase().split(" ");
}
}
AnagramString
package interview;
import java.util.*;
public class AnagramString {
public static void main(String[] args)
{
String s1 ="mang o";
String s2 ="Nam go";
System.out.println(s1+" & "+s2);
checkAnagram(s1,s2);
}
private static void checkAnagram(String s1, String s2)
{
/*
* remove white space
* remove case
* check for count
*/
String a = s1.replace(" ", "").toLowerCase();
String b = s2.replace(" ", "").toLowerCase();
char[] ch1 = a.toCharArray();
char[] ch2 = b.toCharArray();
Arrays.sort(ch1);
Arrays.sort(ch2);
if(Arrays.equals(ch1,ch2))
{
System.out.println("Yes It is Anagram");
}
else
System.out.println("Not Anagram");
}
}
import java.util.*;
public class AnagramString {
public static void main(String[] args)
{
String s1 ="mang o";
String s2 ="Nam go";
System.out.println(s1+" & "+s2);
checkAnagram(s1,s2);
}
private static void checkAnagram(String s1, String s2)
{
/*
* remove white space
* remove case
* check for count
*/
String a = s1.replace(" ", "").toLowerCase();
String b = s2.replace(" ", "").toLowerCase();
char[] ch1 = a.toCharArray();
char[] ch2 = b.toCharArray();
Arrays.sort(ch1);
Arrays.sort(ch2);
if(Arrays.equals(ch1,ch2))
{
System.out.println("Yes It is Anagram");
}
else
System.out.println("Not Anagram");
}
}
AnagramString2
package interview;
public class AnagramString2 {
public static void main(String[] args)
{
String s1 ="java";
String s2 ="avaj";
StringBuffer sb = new StringBuffer(s2);
char[] ch = s1.toCharArray();
for (char c : ch)
{
//int index = sb.indexOf(String.valueOf(c)); --or
int index = sb.indexOf(Character.toString(c));
sb.deleteCharAt(index);
}
System.out.println(sb.length()==0?"Anagram":"Not Anagram");
}
}
public class AnagramString2 {
public static void main(String[] args)
{
String s1 ="java";
String s2 ="avaj";
StringBuffer sb = new StringBuffer(s2);
char[] ch = s1.toCharArray();
for (char c : ch)
{
//int index = sb.indexOf(String.valueOf(c)); --or
int index = sb.indexOf(Character.toString(c));
sb.deleteCharAt(index);
}
System.out.println(sb.length()==0?"Anagram":"Not Anagram");
}
}
Check_If_String_Contains_only_Digit
package interview;
public class Check_If_String_Contains_only_Digit {
public static void main(String[] args)
{
String str = "Error 404 detected in server 589.90 ";
char[] ch = str.toCharArray();
System.out.println(ch);
String str2 = str.replaceAll("[^0-9]","");
System.out.println(str2);
}
}
public class Check_If_String_Contains_only_Digit {
public static void main(String[] args)
{
String str = "Error 404 detected in server 589.90 ";
char[] ch = str.toCharArray();
System.out.println(ch);
String str2 = str.replaceAll("[^0-9]","");
System.out.println(str2);
}
}
Count_Character_WithoutLoop
package interview;
//Write a program to find the number of occurrences of a given character in a string without using loop
public class Count_Character_WithoutLoop {
public static void main(String[] args)
{
String str = "This is an apple";
System.out.println("Length Of String:" + str.length());
System.out.println("Length Of String Without a :" + str.replace("a", "").length());
//System.out.println(">>>"+str.replace("a", ""));
int charcount = str.length() - str.replaceAll("a", "").length();
System.out.println("Occurrence Of A Char In String: " + charcount);
}
}
//Write a program to find the number of occurrences of a given character in a string without using loop
public class Count_Character_WithoutLoop {
public static void main(String[] args)
{
String str = "This is an apple";
System.out.println("Length Of String:" + str.length());
System.out.println("Length Of String Without a :" + str.replace("a", "").length());
//System.out.println(">>>"+str.replace("a", ""));
int charcount = str.length() - str.replaceAll("a", "").length();
System.out.println("Occurrence Of A Char In String: " + charcount);
}
}
Count Words
package interview;
public class CountWords {
public static void main(String[] args)
{
String s1 = "All izz well";
String[] str = s1.split(" ");
System.out.println(str.length);
/*String str2 = "This is what is this world in world 45 67 45";
int l = str2.split(" ").length;
System.out.println("len: "+l);*/
/*String s1 = "All~izz~well";
int l = s1.split("~").length;
System.out.println(">>"+l);*/
String[] str2 = {"abc","def","ghi"};
for (String string : str)
{
System.out.print(string+" ");
}
}
}
public class CountWords {
public static void main(String[] args)
{
String s1 = "All izz well";
String[] str = s1.split(" ");
System.out.println(str.length);
/*String str2 = "This is what is this world in world 45 67 45";
int l = str2.split(" ").length;
System.out.println("len: "+l);*/
/*String s1 = "All~izz~well";
int l = s1.split("~").length;
System.out.println(">>"+l);*/
String[] str2 = {"abc","def","ghi"};
for (String string : str)
{
System.out.print(string+" ");
}
}
}
Duplicate Char
package interview;
//count no. of duplicate character occurance
import java.util.*;
//steps:
//string --->char array---->(convert to lowercase)---->hashmap
public class DuplicateChar {
public static void main(String[] args)
{
String str ="programming world445";
char[] ch = str.toCharArray();
char[] upper_ch = convertLower(ch);
System.out.println(upper_ch);
Map<Character, Integer> map = new HashMap<>();
for(char c : upper_ch)
{
if(map.containsKey(c))
{
map.put(c, map.get(c)+1);
}
else
{
map.put(c, 1);
}
}
//****************
for(Map.Entry<Character,Integer>entry : map.entrySet())
{
if(entry.getValue()>1)
{
System.out.println(entry.getKey()+"-->"+entry.getValue());
}
}
}
//***********************************
private static char[] convertLower(char[] ch)
{
for(int i=0;i<ch.length;i++)
{
if(Character.isLetter(ch[i])&& (Character.isLowerCase(ch[i])))
{
ch[i]= Character.toUpperCase(ch[i]);
}
}
return ch;
}
}
//count no. of duplicate character occurance
import java.util.*;
//steps:
//string --->char array---->(convert to lowercase)---->hashmap
public class DuplicateChar {
public static void main(String[] args)
{
String str ="programming world445";
char[] ch = str.toCharArray();
char[] upper_ch = convertLower(ch);
System.out.println(upper_ch);
Map<Character, Integer> map = new HashMap<>();
for(char c : upper_ch)
{
if(map.containsKey(c))
{
map.put(c, map.get(c)+1);
}
else
{
map.put(c, 1);
}
}
//****************
for(Map.Entry<Character,Integer>entry : map.entrySet())
{
if(entry.getValue()>1)
{
System.out.println(entry.getKey()+"-->"+entry.getValue());
}
}
}
//***********************************
private static char[] convertLower(char[] ch)
{
for(int i=0;i<ch.length;i++)
{
if(Character.isLetter(ch[i])&& (Character.isLowerCase(ch[i])))
{
ch[i]= Character.toUpperCase(ch[i]);
}
}
return ch;
}
}
Duplic_Char
package interview;
public class Duplic_Char {
public static void main(String[] args)
{
String str = "abcd defg abd ghi";
//int cnt = 0;
char[] inp = str.toCharArray();
System.out.println("Duplicate Characters are:");
for (int i = 0; i < str.length(); i++)
{
for (int j = i + 1; j < str.length(); j++)
{
if (inp[i] == inp[j])
{
System.out.println(inp[j]);
//cnt++;
break;
}
}
}
}}
public class Duplic_Char {
public static void main(String[] args)
{
String str = "abcd defg abd ghi";
//int cnt = 0;
char[] inp = str.toCharArray();
System.out.println("Duplicate Characters are:");
for (int i = 0; i < str.length(); i++)
{
for (int j = i + 1; j < str.length(); j++)
{
if (inp[i] == inp[j])
{
System.out.println(inp[j]);
//cnt++;
break;
}
}
}
}}
Duplicate Char Display
package interview;
import java.util.*;
public class DuplicateCharDisplay {
public static void main(String[] args)
{
String str = "welcome to apple world";
displayDuplicate(str);
}
private static void displayDuplicate(String str)
{
Map <Character,Integer> map = new HashMap<>();
char [] ch = str.toCharArray();
for(char c : ch)
{
if(!map.containsKey(c))
{
map.put(c, 1);
}
else
{
map.put(c, map.get(c)+1);
}
}
// Now Iterate map
/*for(char c : map.keySet())
{
System.out.println(c +" - "+map.get(c));
}*/
for(Map.Entry<Character,Integer> entry : map.entrySet())
{
if(entry.getValue()>1)
{
System.out.printf("%s : %d %n",entry.getKey(),entry.getValue());
}
}
}
}
import java.util.*;
public class DuplicateCharDisplay {
public static void main(String[] args)
{
String str = "welcome to apple world";
displayDuplicate(str);
}
private static void displayDuplicate(String str)
{
Map <Character,Integer> map = new HashMap<>();
char [] ch = str.toCharArray();
for(char c : ch)
{
if(!map.containsKey(c))
{
map.put(c, 1);
}
else
{
map.put(c, map.get(c)+1);
}
}
// Now Iterate map
/*for(char c : map.keySet())
{
System.out.println(c +" - "+map.get(c));
}*/
for(Map.Entry<Character,Integer> entry : map.entrySet())
{
if(entry.getValue()>1)
{
System.out.printf("%s : %d %n",entry.getKey(),entry.getValue());
}
}
}
}
Duplicate Strings
package interview;
import java.util.*;
public class DuplicateStrings
{
//String-->String.split()--->String[]--->Uppercase--->Hashmap
public static void main(String[] args)
{
String str = "This is what is this world in world 45 67 45";
String[] str2 = str.split(" ");
String[] str3 = toUpperString(str2);
show(str3);
Map<String,Integer> map = new HashMap<>();
for(String s : str3)
{
if(map.containsKey(s))
{
map.put(s,map.get(s)+1);
}
else
{
map.put(s, 1);
}
}
//*****************************
for(Map.Entry<String,Integer> entry : map.entrySet())
{
if(entry.getValue()>1)
{
System.out.println(entry.getKey()+" --->"+entry.getValue());
}
}
}
private static void show(String[] str3)
{
for(String s : str3)
System.out.print(s+" ");
System.out.println("");
}
private static String[] toUpperString(String[] str2)
{
for(int i =0;i<str2.length;i++)
{
str2[i] = str2[i].toUpperCase();
}
return str2;
}
}
import java.util.*;
public class DuplicateStrings
{
//String-->String.split()--->String[]--->Uppercase--->Hashmap
public static void main(String[] args)
{
String str = "This is what is this world in world 45 67 45";
String[] str2 = str.split(" ");
String[] str3 = toUpperString(str2);
show(str3);
Map<String,Integer> map = new HashMap<>();
for(String s : str3)
{
if(map.containsKey(s))
{
map.put(s,map.get(s)+1);
}
else
{
map.put(s, 1);
}
}
//*****************************
for(Map.Entry<String,Integer> entry : map.entrySet())
{
if(entry.getValue()>1)
{
System.out.println(entry.getKey()+" --->"+entry.getValue());
}
}
}
private static void show(String[] str3)
{
for(String s : str3)
System.out.print(s+" ");
System.out.println("");
}
private static String[] toUpperString(String[] str2)
{
for(int i =0;i<str2.length;i++)
{
str2[i] = str2[i].toUpperCase();
}
return str2;
}
}
Fibonacci
package interview;
public class Fibonacci {
public static void main(String[] args)
{
int fib1 = 0;
int fib2 = 1;
int fib3;
int limit = 10;
System.out.println("First "+limit+" terms");
for(int i = 1; i<limit;++i)
{
System.out.println(fib1);
fib3 = fib1+ fib2;
fib1 = fib2;
fib2 = fib3;
}
}
}
public class Fibonacci {
public static void main(String[] args)
{
int fib1 = 0;
int fib2 = 1;
int fib3;
int limit = 10;
System.out.println("First "+limit+" terms");
for(int i = 1; i<limit;++i)
{
System.out.println(fib1);
fib3 = fib1+ fib2;
fib1 = fib2;
fib2 = fib3;
}
}
}
First Non Repeated Character
package interview;
import java.util.*;
//Print first Non Repeated character
public class FirstNonRepeatedCharacter {
public static void main(String[] args)
{
String str = "computercomputes";
char[] ch = str.toCharArray();
LinkedHashMap<Character,Integer> link = new LinkedHashMap<>();
for(int i = 0;i<ch.length;i++)
{
if(link.containsKey(ch[i]))
{
link.put(ch[i], link.get(ch[i])+1);
}
else
{
link.put(ch[i],1);
}
}
//***Iterate
for(Map.Entry<Character,Integer> entry : link.entrySet())
{
if(entry.getValue()==1)
{
System.out.println("first NRC: "+entry.getKey());
System.out.println("first NRC: "+entry.getKey().toString().toUpperCase());
return;
}
}
}
}
import java.util.*;
//Print first Non Repeated character
public class FirstNonRepeatedCharacter {
public static void main(String[] args)
{
String str = "computercomputes";
char[] ch = str.toCharArray();
LinkedHashMap<Character,Integer> link = new LinkedHashMap<>();
for(int i = 0;i<ch.length;i++)
{
if(link.containsKey(ch[i]))
{
link.put(ch[i], link.get(ch[i])+1);
}
else
{
link.put(ch[i],1);
}
}
//***Iterate
for(Map.Entry<Character,Integer> entry : link.entrySet())
{
if(entry.getValue()==1)
{
System.out.println("first NRC: "+entry.getKey());
System.out.println("first NRC: "+entry.getKey().toString().toUpperCase());
return;
}
}
}
}
Palindrom_Num
package interview;
public class Palindrom_Num {
//reverse karke check kar lo
public static void main(String[] args)
{
int a = 121;
int t = a;
int rev=0;
int temp = 0;
while(a>0)
{
temp = a%10;
rev = (rev*10)+temp;
a= a/10;
}
if(t == rev)
System.out.println("Palindrom");
else
System.out.println("Not Palindrom");
//Method 2: Starts ***********************************************
int num2 = 1210121;
StringBuffer sb7 = new StringBuffer(num2);
if(sb7==sb7.reverse())
System.out.println(num2+" : is Pelindrom");
else
System.out.println(num2+" : is Not Pelindrom");
//Method 2 :Ends ***********************************************
}
}
public class Palindrom_Num {
//reverse karke check kar lo
public static void main(String[] args)
{
int a = 121;
int t = a;
int rev=0;
int temp = 0;
while(a>0)
{
temp = a%10;
rev = (rev*10)+temp;
a= a/10;
}
if(t == rev)
System.out.println("Palindrom");
else
System.out.println("Not Palindrom");
//Method 2: Starts ***********************************************
int num2 = 1210121;
StringBuffer sb7 = new StringBuffer(num2);
if(sb7==sb7.reverse())
System.out.println(num2+" : is Pelindrom");
else
System.out.println(num2+" : is Not Pelindrom");
//Method 2 :Ends ***********************************************
}
}
Prime Numbers
package interview;
public class Prime {
public static void main(String[] args)
{
boolean flag = false;
int num = 127;
for(int i = 2;i<Math.sqrt(num)+1;i++)
{
if(num%i == 0)
{
flag = true;
}
}
System.out.println(flag == true ? Not Prime : Prime);
}
}
public class Prime {
public static void main(String[] args)
{
boolean flag = false;
int num = 127;
for(int i = 2;i<Math.sqrt(num)+1;i++)
{
if(num%i == 0)
{
flag = true;
}
}
System.out.println(flag == true ? Not Prime : Prime);
}
}
Reverse_Each_Word
package interview;
public class Reverse_Each_Word
{
public static void main(String[] args)
{
String s1 = "java programming uses JVM";
String[] s2 = s1.split(" "); //[java , programming]
String rev = "";
for(int i = 0;i<s2.length;i++)
{
String s = s2[i]; //java
for(int j =s.length()-1; j>=0 ;j--)
{
rev = rev + s.charAt(j);
}
rev= rev +" ";
}
System.out.println("Original: "+s1);
System.out.println("Reversed: "+rev);
}
}
public class Reverse_Each_Word
{
public static void main(String[] args)
{
String s1 = "java programming uses JVM";
String[] s2 = s1.split(" "); //[java , programming]
String rev = "";
for(int i = 0;i<s2.length;i++)
{
String s = s2[i]; //java
for(int j =s.length()-1; j>=0 ;j--)
{
rev = rev + s.charAt(j);
}
rev= rev +" ";
}
System.out.println("Original: "+s1);
System.out.println("Reversed: "+rev);
}
}
RemoveSpace
package interview;
//Remove white space
public class RemoveSpace {
public static void main(String[] args)
{
//*******************************************
String s1 = "remove white space";
String s2 = s1.replaceAll("\\s","");
String s4 = s1.replaceAll("\\s","~");
System.out.println(s2);
System.out.println(s4);
//*******************************************
String s3 = "remove white space";
char[] ch = s3.toCharArray();
StringBuffer sb = new StringBuffer();
for(char c : ch)
{
if (c!=' ')
{
sb = sb.append(c);
}
}
System.out.println(sb);
}
}
//Remove white space
public class RemoveSpace {
public static void main(String[] args)
{
//*******************************************
String s1 = "remove white space";
String s2 = s1.replaceAll("\\s","");
String s4 = s1.replaceAll("\\s","~");
System.out.println(s2);
System.out.println(s4);
//*******************************************
String s3 = "remove white space";
char[] ch = s3.toCharArray();
StringBuffer sb = new StringBuffer();
for(char c : ch)
{
if (c!=' ')
{
sb = sb.append(c);
}
}
System.out.println(sb);
}
}
ReverseEachSring_StringBuffer
package interview;
public class ReverseEachSring_StringBuffer {
public static void main(String[] args)
{
String s1 = "java programming uses JVM";
String[] s2 = s1.split(" "); //[java , programming]
StringBuffer buffer =new StringBuffer();
for(int i = 0;i<s2.length;i++)
{
for(int j =s2[i].length()-1; j>=0 ;j--)
{
buffer = buffer.append(s2[i].charAt(j));
}
buffer = buffer.append(" ");
}
System.out.println("Original: "+s1);
System.out.println("Reversed: "+buffer);
}
}
public class ReverseEachSring_StringBuffer {
public static void main(String[] args)
{
String s1 = "java programming uses JVM";
String[] s2 = s1.split(" "); //[java , programming]
StringBuffer buffer =new StringBuffer();
for(int i = 0;i<s2.length;i++)
{
for(int j =s2[i].length()-1; j>=0 ;j--)
{
buffer = buffer.append(s2[i].charAt(j));
}
buffer = buffer.append(" ");
}
System.out.println("Original: "+s1);
System.out.println("Reversed: "+buffer);
}
}
ReverseEachString_CharArray
package interview;
public class ReverseEachString_CharArray
{
public static void main(String[] args)
{
String s1 = "java programming uses JVM";
String rev ="";
String[] s2 = s1.split(" ");
System.out.println(s1);
for(String s : s2)
{
char[] ch = s.toCharArray();
for(int i =ch.length-1 ;i>=0;i--)
{
System.out.print(ch[i]);
}
System.out.print(" ");
}
}
}
public class ReverseEachString_CharArray
{
public static void main(String[] args)
{
String s1 = "java programming uses JVM";
String rev ="";
String[] s2 = s1.split(" ");
System.out.println(s1);
for(String s : s2)
{
char[] ch = s.toCharArray();
for(int i =ch.length-1 ;i>=0;i--)
{
System.out.print(ch[i]);
}
System.out.print(" ");
}
}
}
Subscribe to:
Comments (Atom)
-
Exception in thread "main" java.lang.IllegalStateException: Cannot get a STRING value from a NUMERIC cell at org.apache.poi.xss...
-
package multithreading; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; class MyThread4 extends...
-
package multithreading; import java.util.concurrent.locks.ReentrantLock; class MyyThread extends Thread { static ReentrantLock l = n...