import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ArrayShuffle {
public static void main(String[] args) {
// Initialize the contents of our array
String[] alphabets = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
// As the Collections.shuffle method need a list for the parameter we
// convert our array into List using the Arrays class.
List<String> list = Arrays.asList(alphabets);
// Here we just simply used the shuffle method of Collections class
// to shuffle out defined array.
Collections.shuffle(list);
// Run the code again and again, then you'll see how simple we do shuffling
for (String alpha : list) {
System.out.print(alpha + " ");
}
}
}
Showing posts with label Collections. Show all posts
Showing posts with label Collections. Show all posts
Tuesday, March 6, 2012
How do I shuffle elements of an array in Java?
How do I create an empty collection object in Java?
Sometimes you need to return an empty collection from your Java methods. Javajava.util.Collections class have three different static instances for creating empty List, Set and Map. There are also methods when you want to create type-safe empty collections. Bellow it the code example.
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.Date;
public static void main(String args[])
{
List list = Collections.EMPTY_LIST;
Set set = Collections.EMPTY_SET;
Map map = Collections.EMPTY_MAP;
// For the type-safe example use the following methods.
List<String> s = Collections.emptyList();
Set<Long> l = Collections.emptySet();
Map<Date> d = Collections.emptyMap();
}
How do I sort an array of objects in java?
import java.util.Arrays;
public class ObjectSortExample {
public static void main(String[] args) {
// Here we have a list of people name, it is balinese people
// name.
String names[] = {"Wayan", "Made", "Nyoman", "Ketut"};
// We can order them by their name and write to the screen.
// It's just like sorting a primitive array.
Arrays.sort(names);
for (int i = 0; i < names.length; i++) {
String name = names[i];
System.out.print("name = " + name + "; ");
}
System.out.println("");
// Now we will sort an array of our own object. It is a bit
// different compared to sorting an array of primitives. The
// first rule is we need our object to implements the
// Comparable interface. This interface have one contract we
// need to implement, the compareTo() contract. See the Person
// class below.
// Here we create four Person objects, and set their name.
// After that we sort the Person object based on their name
// using the Arrays.sort() method.
Person persons[] = new Person[4];
persons[0] = new Person("Wayan");
persons[1] = new Person("Made");
persons[2] = new Person("Nyoman");
persons[3] = new Person("Ketut");
Arrays.sort(persons);
for (int i = 0; i < persons.length; i++) {
Person person = persons[i];
System.out.println("person = " + person);
}
}
}
// As mentioned above that to be sortable by Arrays.sort() method our
// class need to implements the compareTo(Object obj) method which is
// a contract defined in the Comparable interface.
class Person implements Comparable {
private String name;
// A constructor to Person class.
public Person(String name) {
this.name = name;
}
// Here is our compareTo implementation, here we just delegate
// the compareTo to the string object compareTo method. The basic
// rule for this method to return are: 0 when objects value are
// equals; 1 if this object value is greater; and -1 if this object
// value is smaller.
public int compareTo(Object o) {
Person p = (Person) o;
return this.name.compareTo(p.name);
}
// Override toString() to return a readable person name.
public String toString() {
return name;
}
}
How do I sort elements of an array?
import java.util.Arrays;
public class ArraySortExample {
public static void main(String[] args) {
// An array of random numbers
int numbers[] = {3, 1, 8, 34, 1, 2, 13, 89, 5, 21, 55};
System.out.print("Before: ");
for (int i = 0; i < numbers.length; i++) {
int number = numbers[i];
System.out.print(number + "; ");
}
System.out.println("");
// We need to sort these array elements into a correct
// order from the smallest to the greatest.
// We will use the Arrays class on java.utils package to do
// the sort. The sort method of this class are overloaded,
// so they can take other type of array as well such as byte[]
// long[], float[], Object[].
Arrays.sort(numbers);
System.out.print("After: ");
for (int i = 0; i < numbers.length; i++) {
int number = numbers[i];
System.out.print(number + "; ");
}
System.out.println("");
// We can also do the sort only for the specified range of
// array elements.
float money[] = {1.05f, 99.8f, 3f, 4.55f, 7.23f, 6.50f};
Arrays.sort(money, 3, money.length);
// Here we display the sort result, the first and the second
// element of the array is not included in the sort process.
for (int i = 0; i < money.length; i++) {
float v = money[i];
System.out.print(v + "; ");
}
}
}
Monday, March 5, 2012
How do I know the minimum and maximum number in array in android?
import java.util.Arrays;
import java.util.Collections;
public class ArrayMinMax {
public static void main(String[] args)
{
// Creates an array of integer numbers in it.
Integer[] numbers = { 8, 2, 6, 7, 0, 1, 4, 9, 5, 3 };
// To get the minimum or maximum value from the array we can
// use the Collections.min() and Collections.max() methods.
// But as this method requires a list type of data we need
// to convert the array to list first.
int min = (int) Collections.min(Arrays.asList(numbers));
int max = (int) Collections.max(Arrays.asList(numbers));
// Viola! we get the minimum and the maximum value from the
// array.
System.out.println("Min number: " + min);
System.out.println("Max number: " + max);
}
}
Below is the output...
Min number: 0
Max number: 9
How do I convert an array to a Map in android?
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
public class ArrayToMapExample {
public static void main(String[] args) {
//
// A two dimensional array of countries capital.
//
String[][] countries = {{"United States", "New York"},
{"United Kingdom", "London"},
{"Netherlands", "Amsterdam"},
{"Japan", "Tokyo"},
{"France", "Paris"}};
//
// To convert an array to a Map each array elements must
// be an array with at least two elements where the first
// element will be the key and the second element will be
// the value.
//
Map countryCapitals = ArrayUtils.toMap(countries);
System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));
System.out.println("Capital of France is " + countryCapitals.get("France"));
}
}
How do I use the HashMap class in Android?
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HashMapDemo {
public static void main(String[] args) {
Map 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 errorDesc = (String) errors.get("404");
System.out.println("Error 404: " + errorDesc);
// iterating the map by it's keys
Iterator iterator = errors.keySet().iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
System.out.println("Error " + key + " means " + errors.get(key));
}
}
}
How do I reverse array elements order in Java?
import org.apache.commons.lang.ArrayUtils;
public class ArrayReverseExample {
public static void main(String[] args) {
//
// Define colors array.
//
String[] colors = {"Red", "Green", "Blue", "Cyan", "Yellow", "Magenta"};
System.out.println(ArrayUtils.toString(colors));
//
// Now we reverse the order of array elements using the ArrayUtils.reverse()
// method. The reverse method is overloaded so we can reverse other type
// of array such as boolean, char, byte, double, etc.
//
ArrayUtils.reverse(colors);
System.out.println(ArrayUtils.toString(colors));
}
}
How do I Convert Collection to ArrayList in android?
import java.util.ArrayList;
import java.util.LinkedList;
public class CollectionToArrayList
{
public static void main(String[] args)
{
// We create LinkedList collection type at put some values
// in it. Here we put A, B, C and D letter into it.
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.push("A");
linkedList.push("B");
linkedList.push("C");
linkedList.push("D");
// Let say you want to convert it to other type of collection,
// for instance here we convert it into ArrayList. To do it
// we can pass the collection created above as a parameter to
// ArrayList constructor.
ArrayList<String> arrayList = new ArrayList<String>(linkedList);
// Now we have converted the collection into ArrayList and
// printed what is inside.
for (String s : arrayList)
{
System.out.println("s = " + s);
}
}
}
How do I remove duplicate element from array in Android?
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ArrayRemoveDuplicate {
public static void main(String[] args) {
//
// A string array with duplicate values
//
String[] data = {
"A", "C", "B", "D", "A", "B", "E", "D", "B", "C"
};
System.out.println("Original array : " +
Arrays.toString(data));
//
// Convert it to list as we need the list object to create a
// set object. A set is a collection object that cannot have
// a duplicate values, so by converting the array to a set
// the duplicate value will be removed.
//
List<String> list = Arrays.asList(data);
Set<String> set = new HashSet<String>(list);
System.out.print("Remove duplicate result: ");
//
// Create an array to convert the Set back to array.
// The Set.toArray() method copy the value in the set to the
// defined array.
//
String[] result = new String[set.size()];
set.toArray(result);
for (String s : result) {
System.out.print(s + ", ");
}
}
}
How do I sort items in a Set in Android?
import java.util.Set;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
//
// The TreeSet class is an implementation of a SortedSet, this means
// that when your are using the TreeSet to store you data collections
// you'll get the items ordered base on its elements natural order.
//
Set<String> set = new TreeSet<String>();
//
// In the example below we add some letters to the TreeSet, this mean
// that the alphabets will be ordered based on the alphabet order
// whichs is from A to Z.
//
set.add("Z");
set.add("A");
set.add("F");
set.add("B");
set.add("H");
set.add("X");
set.add("N");
for (String item : set) {
System.out.print(item + " ");
}
}
}
Sunday, March 4, 2012
How do I convert array to Set in Java?
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 Set first we convert it to a List. Next
// with the list we create a HashSet and pass the list as the constructor.
//
List list = Arrays.asList(numbers);
Set set = new HashSet(list);
//
// Display what we get in the set.
//
for (Iterator iterator = set.iterator(); iterator.hasNext();) {
Object o = iterator.next();
System.out.print(o + ", ");
}
}
}
How do I sort items of an ArrayList in Java?
This example shows you how we can sort items of an ArrayList using the Collections.sort()method. Beside accepting the list object to be sorted we can also pass a Comparator implementation to define the sorting behavior such as sorting in descending or ascending order.
public class ArrayListSortExample {
public static void main(String[] args) {
/*
* Create a collections of colours
*/
List colours = new ArrayList();
colours.add("red");
colours.add("green");
colours.add("blue");
colours.add("yellow");
colours.add("cyan");
colours.add("white");
colours.add("black");
/*
* We can sort items of a list using the Collections.sort() method.
* We can also reverse the order of the sorting by passing the
* Collections.reverseOrder() comparator.
*/
Collections.sort(colours);
System.out.println(Arrays.toString(colours.toArray()));
Collections.sort(colours, Collections.reverseOrder());
System.out.println(Arrays.toString(colours.toArray()));
}
}
Below is the output...
[black, blue, cyan, green, red, white, yellow]
[yellow, white, red, green, cyan, blue, black]
Subscribe to:
Posts (Atom)