package org.kodejava.util;
import java.util.*;
public class ArrayToSetExample {
public static void main(String[] args) {
Integer[] numbers = {7, 7, 8, 9, 10, 8, 8, 9, 6, 5, 4};
// To convert an array into a java.util.Set firstly we need to convert the
// array into a java.util.List using the Arrays.asList() method. With the
// List object created we can instantiate a new java.util.HashSet and pass
// the list as the constructor parameter.
List<Integer> numberList = Arrays.asList(numbers);
Set<Integer> numberSet = new HashSet<>(numberList);
// Or we can simply combine the line above into single line.
Set<Integer> anotherNumberSet = new HashSet<>(Arrays.asList(numbers));
// Display what we get in the set using iterator.
for (Iterator<Integer> iterator = numberSet.iterator(); iterator.hasNext(); ) {
Integer number = iterator.next();
System.out.print(number + ", ");
}
// Display what we get in the set using for-each.
for (Integer number : anotherNumberSet) {
System.out.print(number + ", ");
}
}
}
How do I use the HashMap class?
This example demonstrate you how to use the HashMap class to store values in a key-value structure. In this example we store a map of error codes with their corresponding description. To store a value into the map we use the put(key, value) method and to get it back we use the get(key) method. And we can also iterate the map using the available key sets of the map.
package org.kodejava.util;
import java.util.HashMap;
import java.util.Map;
public class HashMapDemo {
public static void main(String[] args) {
Map<String, String> errors = new HashMap<>();
// mapping some data in the map
errors.put("404", "Resource not found");
errors.put("403", "Access forbidden");
errors.put("500", "General server error");
// reading data from the map
String errorDescription = errors.get("404");
System.out.println("Error 404: " + errorDescription);
// Iterating the map by the keys
for (String key : errors.keySet()) {
System.out.println("Error " + key + ": " + errors.get(key));
}
}
}
The result of the code snippet above:
Error 404: Resource not found
Error 500: General server error
Error 403: Access forbidden
Error 404: Resource not found
How do I generate a random array of numbers?
Using java.util.Random class we can create random data such as boolean, integer, floats, double. First you’ll need to create an instance of the Random class. This class has some next***() methods that can randomly create the data.
package org.kodejava.util;
import java.util.Arrays;
import java.util.Random;
public class RandomDemo {
public static void main(String[] args) {
Random r = new Random();
// generate some random boolean values
boolean[] booleans = new boolean[10];
for (int i = 0; i < booleans.length; i++) {
booleans[i] = r.nextBoolean();
}
System.out.println(Arrays.toString(booleans));
// generate a uniformly distributed int random numbers
int[] integers = new int[10];
for (int i = 0; i < integers.length; i++) {
integers[i] = r.nextInt();
}
System.out.println(Arrays.toString(integers));
// generate a uniformly distributed float random numbers
float[] floats = new float[10];
for (int i = 0; i < floats.length; i++) {
floats[i] = r.nextFloat();
}
System.out.println(Arrays.toString(floats));
// generate a Gaussian normally distributed random numbers
double[] doubles = new double[10];
for (int i = 0; i < doubles.length; i++) {
doubles[i] = r.nextGaussian();
}
System.out.println(Arrays.toString(doubles));
}
}
The result of the code snippet above are:
[true, true, false, true, false, true, true, false, false, true]
[34195704, 1462972230, -475641915, -1531017612, 332184915, 1555901473, -276309016, 1433394157, -451221924, -1178823255]
[0.3040716, 0.28814012, 0.34028566, 0.021003246, 0.49158317, 0.37954164, 0.5403056, 0.54187375, 0.7157934, 0.5964742]
[1.051268591002577, -1.1283332046139989, 0.8351395528722437, -0.24598168031182968, 0.7123515366756693, -0.9661681996105319, -1.6107009669125059, 0.43994917963255387, 1.1309345726165914, 1.2321618489324313]
For an example to create random number using the Math.random() method see How do I create random number?.
How do I reverse a string by word?
In the other examples on this website you might have seen how to reverse a string using StringBuffer, StringUtils from Apache Commons Lang library or using the CharacterIterator.
In this example you’ll see another way that you can use to reverse a string by word. Here we use the StringTokenizer and the Stack class.
package org.kodejava.util;
import java.util.Stack;
import java.util.StringTokenizer;
public class ReverseStringByWord {
public static void main(String[] args) {
// The string that we'll reverse
String text = "Jackdaws love my big sphinx of quartz";
// We use StringTokenize to get each word of the string. You might try
// to use the String.split() method if you want.
StringTokenizer st = new StringTokenizer(text, " ");
// To reverse it we can use the Stack class, which implements the LIFO
// (last-in-first-out).
Stack<String> stack = new Stack<>();
while (st.hasMoreTokens()) {
stack.push(st.nextToken());
}
// Print each word in reverse order
while (!stack.isEmpty()) {
System.out.print(stack.pop() + " ");
}
}
}
How do I convert varargs to an array?
Varargs can be seen as a simplification of array when we need to pass a multiple value as a method parameter. Varargs itself is an array that automatically created, for these reason you will be enabled to do things you can do with array to varargs.
In the example below you can see the messages parameter can be assigned to the String array variables, we can call the length method to the messages parameter as we do with the array. So actually you don’t need to convert varargs to array because varargs is array.
package org.kodejava.lang;
public class VarargsToArray {
public static void main(String[] args) {
printMessage("Hello ", "there", ", ", "how ", "are ", "you", "?");
}
public static void printMessage(String... messages) {
String[] copiedMessage = messages;
for (int i = 0; i < messages.length; i++) {
System.out.print(copiedMessage[i]);
}
}
}
