Java – Bubble Sort Array Example

import java.util.Arrays;

/**
 * Algorithm
 *
 * 1] Compare each pair of adjacent elements from beginning
 * of an array and, if they are in reversed order, swap them.
 *
 * 2] If at least one swap has been done, repeat step 1.
 *
 */
public class MyBubbleSort {

	private void sortData(int[] data) {
		boolean swapDone = false;
		do {
			swapDone = false;
			for (int i = 0; i < data.length-1; i++) {
				if (data[i] > data[i+1]) {
					swapDone = true;
					int tmp = data[i];
					data[i] = data[i+1];
					data[i+1] = tmp;
				}
			}
		} while (swapDone == true);
	}

	public static void main(String[] args) {
		int[] data = {5,1,12,-5,16};
		System.out.println(Arrays.toString(data));

		new MyBubbleSort().sortData(data);
		System.out.println(Arrays.toString(data));
	}

}

Java – Convert Array to Map using Commons ArrayUtils

This example use the Apache Commons lang’s ArrayUtils class to convert a two dimensional array to a Map object.

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"));
	}

}

Java – Convert Array to List

import java.util.*;
import java.io.*;

public class ArrayToCollection {

	public static void main(String args[]) throws IOException {

		BufferedReader in = new BufferedReader
				(new InputStreamReader(System.in));
		System.out.println("How many elements you want to add to the array: ");
		int n = Integer.parseInt(in.readLine());
		String[] name = new String[n];
		for(int i = 0; i < n; i++) {
			name[i] = in.readLine();
		}
		List list = Arrays.asList(name);
		System.out.println();
		for(String li: list) {
			String str = li;
			System.out.print(str + " ");
		}

	}

}

Output:

How many elements you want to add to the array:
red white green

red white green

Page 1 of 212