Array & Set Example: Character vowel[] = { 'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U' }; Set<Character> v = new HashSet<>(Arrays.asList(vowel)); StringBuilder & String Example: StringBuffer sb = new StringBuffer(); String str = sb.toString();
How to convert List to Int Array in Java
We create a new list: List<Integer> result = new ArrayList<Integer>(); Finally we convert it to int array and return this array: return result.stream().mapToInt(i -> i).toArray();
Comparator Interface in Java
Comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of two different classes. Method 1: One obvious approach is to write our own sort() function using one of the standard algorithms. This solution requires rewriting the whole sorting code for different criterion like Roll …
Conversion between String and Integer in java
From String to Integer Integer.parseInt(my_string); From Integer to String Integer.toString(my_integer);
Difference between == and .equals() method in Java
In general both equals() and “==” operator in Java are used to compare objects to check equality but here are some of the differences between the two: Main difference between .equals() method and == operator is that one is method and other is operator. We can use == operators for reference comparison (address comparison) and …
Continue reading “Difference between == and .equals() method in Java”
Sorting a HashMap according to keys in Java
Using TreeMap // Java Code to sort Map by key value import java.util.*; class sortmapKey { // This map stores unsorted values static Map<String, Integer> map = new HashMap<>(); // Function to sort map by Key public static void sortbykey() { // TreeMap to store values of HashMap TreeMap<String, Integer> sorted = new TreeMap<>(); // …
Continue reading “Sorting a HashMap according to keys in Java”
Java Iterate through a HashMap Example
Using for each to iterate through a HashMap Using for each to iterate through a HashMap import java.util.HashMap; import java.util.Map; public class IterateHashMap { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("key1", "value1"); map.put("key2", "value2"); for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println(entry.getKey() + " = " + entry.getValue()); …
When I try to add List to List in Java
I faced a problem when I try to add List to List< List > in java, and it did consume some my time. It is a common problem and I even can remember I got stuck on debugging because of this "feature" at least twice. To let me remember this problem and avoid making it …