Tuesday, 5 February 2019

4.How to remove duplicate Characters from a String in java.


Description:
Write a sample code to remove duplicate Characters from a String.

Code:
?
1
2
3
4
5
6
7
8
9
10

import java.util.HashSet;
import java.util.Set;

public class RemoveDuplicate {
public static void main(String[] args) {
String str = "godblessgovind";
char[] characters = str.toCharArray();
Set set = new HashSet();
StringBuilder sb = new StringBuilder();
System.out.println("String with duplicates : " + str);
for (char c : characters) {
if (!set.contains(c)) {
set.add(c);
sb.append(c);
}
}
System.out.println("String after duplicates removed : " + sb.toString());
}
}

Output:
String with duplicates : godblessgovind
String after duplicates removed : godblesvin

3.How to print all map values in java.


Description:
Write a sample code to print all map values.


Code:
?

1
2
3
4
5
6
7
8
9
10

import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class PrintMapvalue { public static void main(String[] args) { HashMap<String, String> hmap = new HashMap<String, String>(); hmap.put("1000", "God"); hmap.put("2000", "Bless"); hmap.put("3000", "Govind"); Collection c = hmap.values(); Iterator itr = c.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } } }

Output:
God
Bless
Govind

2. Count occurrences of character in string java using hashmap

Description:
Write a sample code to Count occurrences of character in string.

Code:
?
1
2
3
4
5
6
7
8
9
10

import java.util.HashMap; public class NO_of_Occurance { public static void main(String[] args) { String str = "Programming"; HashMap<Character, Integer> map = new HashMap<>(); for (char ch : str.toCharArray()) { if (map.containsKey(ch)) { int val = map.get(ch); map.put(ch, val + 1); } else { map.put(ch, 1); } } System.out.println(map); } }





Output:
{P=1, a=1, r=2, g=2, i=1, m=2, n=1, o=1}

1. How to find Reverse Sting in java.


Description:
Write a sample code to reverse String.

Code:
?
1
2
3
4
5
6
7
8

 import java.util.Scanner; public class ReverseString { public static void main(String[] args) { String Original, reverse = " "; Scanner s = new Scanner(System.in); System.out.println("Enter String for reverse:"); Original = s.nextLine(); int length = Original.length(); for (int i = length - 1; i >= 0; i--) reverse = reverse + Original.charAt(i); System.out.println("Rverse of entered String is:" + reverse); } }





Input:
Enter String for reverse: godblessgovind
Output:
Rverse of entered String is: dnivogsselbdog