Sei sulla pagina 1di 20

How to union, intersect, difference and reverse data in java

Set<Integer> a = new TreeSet<Integer>(Arrays.asList(new Integer[]{0,2,4,5,6,8,10})); Set<Integer> b = new TreeSet<Integer>(Arrays.asList(new Integer[]{5,6,7,8,9,10})); //union Set<Integer> c = new TreeSet<Integer>(a); c.addAll(b); System.out.println(c);

//intersection Set<Integer> d = new TreeSet<Integer>(a); d.retainAll(b); System.out.println(d);

//difference Set<Integer> e = new TreeSet<Integer>(a); e.removeAll(b); System.out.println(e);

//reverse List<Integer> list = new ArrayList<Integer>(a); java.util.Collections.reverse(list); System.out.println(list);

Set subtraction
import java.util.HashSet; import java.util.Set; public class FindDupsAndUnique { public static void main(String args[]) { Set uniques = new HashSet(); Set dups = new HashSet(); String[] values = new String[] { "java", "java2", "java2s", "javas", "java" }; for (int i = 0; i < values.length; i++) if (!uniques.add(values[i])) dups.add(values[i]); uniques.removeAll(dups); // Destructive set-difference System.out.println("Unique words: " + uniques); System.out.println("Duplicate words: " + dups); } }

Using an Error Page Jsp


//File: index.jsp <%@ page errorPage="errorPage.jsp" %> <HTML> <HEAD> <TITLE>Using an Error Page</TITLE> </HEAD> <BODY> <H1>Using an Error Page</H1> <% int value = 1; value = value / 0; %> </BODY> </HTML>

//File: errorPage.jsp <%@ page isErrorPage="true" %> <HTML> <HEAD> <TITLE>An Error Page</TITLE> </HEAD>

<BODY> <H1>An Error Page</H1> There was an error! Don't Panic!!! <BR> Consult your physician immediately. </BODY> </HTML>

Set operations: union, intersection, difference, symmetric difference, is subset, is superset


import java.util.Set; import java.util.TreeSet; public class Main { public static <T> Set<T> union(Set<T> setA, Set<T> setB) { Set<T> tmp = new TreeSet<T>(setA); tmp.addAll(setB); return tmp; } public static <T> Set<T> intersection(Set<T> setA, Set<T> setB) { Set<T> tmp = new TreeSet<T>(); for (T x : setA) if (setB.contains(x)) tmp.add(x); return tmp; } public static <T> Set<T> difference(Set<T> setA, Set<T> setB) { Set<T> tmp = new TreeSet<T>(setA); tmp.removeAll(setB); return tmp; } public static <T> Set<T> symDifference(Set<T> setA, Set<T> setB) { Set<T> tmpA; Set<T> tmpB; tmpA = union(setA, setB); tmpB = intersection(setA, setB); return difference(tmpA, tmpB); } public static <T> boolean isSubset(Set<T> setA, Set<T> setB) { return setB.containsAll(setA); }

public static <T> boolean isSuperset(Set<T> setA, Set<T> setB) { return setA.containsAll(setB); } public static void main(String args[]) { TreeSet<Character> set1 = new TreeSet<Character>(); TreeSet<Character> set2 = new TreeSet<Character>(); set1.add('A'); set1.add('B'); set1.add('C'); set1.add('D'); set2.add('C'); set2.add('D'); set2.add('E'); set2.add('F'); System.out.println("set1: " + set1); System.out.println("set2: " + set2); System.out.println("Union: " + union(set1, set2)); System.out.println("Intersection: " + intersection(set1, set2)); System.out.println("Difference (set1 set2): " + difference(set1, set2)); System.out.println("Symmetric Difference: " + symDifference(set1, set2)); TreeSet<Character> set3 = new TreeSet<Character>(set1); set3.remove('D'); System.out.println("set3: " + set3); System.out.println("Is set1 a subset of set2? " + isSubset(set1, set3)); System.out.println("Is set1 a superset of set2? " + isSuperset(set1, set3 )); System.out.println("Is set3 a subset of set1? " + isSubset(set3, set1)); System.out.println("Is set3 a superset of set1? " + isSuperset(set3, set1 )); } }

Set, HashSet and TreeSet


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

public class Main { public static void main(String args[]) { Set<String> hs = new HashSet<String>(); hs.add("one"); hs.add("two"); hs.add("three"); System.out.println("Here is the HashSet: " + hs); if (!hs.add("three")) System.out.println("Attempt to add duplicate. " + "Set is unchanged: " + hs); TreeSet<Integer> ts = new TreeSet<Integer>(); ts.add(8); ts.add(19); ts.add(-2); ts.add(3); System.out.println(ts); System.out.println("First element in ts: " + ts.first()); System.out.println("Last element in ts: " + ts.last()); System.out.println("First element > 15: " + ts.higher(15)); System.out.println("First element < 15: " + ts.lower(15)); } }

Things you can do with Sets


import import import import import java.util.Arrays; java.util.HashSet; java.util.LinkedHashSet; java.util.Set; java.util.TreeSet;

public class Set1 { static void fill(Set s) { s.addAll(Arrays.asList("one two three four five six seven".split(" "))); } public static void test(Set s) { // Strip qualifiers from class name:

System.out.println(s.getClass().getName().replaceAll("\\w+\\.", "")); fill(s); fill(s); fill(s); System.out.println(s); // No duplicates! // Add another set to this one: s.addAll(s); s.add("one"); s.add("one"); s.add("one"); System.out.println(s); // Look something up: System.out.println("s.contains(\"one\"): " + s.contains("one")); } public static void main(String[] args) { test(new HashSet()); test(new TreeSet()); test(new LinkedHashSet()); } }

Set that compares object by identity rather than equality


import import import import import java.util.Collection; java.util.IdentityHashMap; java.util.Iterator; java.util.Map; java.util.Set;

/** * Set that compares object by identity rather than equality. Wraps around a <code>IdentityHashMap</code> * * @author Emmanuel Bernard */ public class IdentitySet implements Set { private Map<Object, Object> map; private Object CONTAINS = new Object(); public IdentitySet() { this( 10 ); } public IdentitySet(int size) { this.map = new IdentityHashMap<Object, Object>( size ); }

public int size() { return map.size(); } public boolean isEmpty() { return map.isEmpty(); } public boolean contains(Object o) { return map.containsKey( o ); } public Iterator iterator() { return map.keySet().iterator(); } public Object[] toArray() { return map.keySet().toArray(); } public boolean add(Object o) { return map.put( o, CONTAINS ) == null; } public boolean remove(Object o) { return map.remove( o ) == CONTAINS; } public boolean addAll(Collection c) { boolean doThing = false; for ( Object o : c ) { doThing = doThing || add( o ); } return doThing; } public void clear() { map.clear(); } public boolean removeAll(Collection c) { boolean remove = false; for ( Object o : c ) { remove = remove || remove( o ); } return remove; }

public boolean retainAll(Collection c) { throw new UnsupportedOperationException(); } public boolean containsAll(Collection c) { for ( Object o : c ) { if ( !contains( o ) ) { return false; } } return true; } public Object[] toArray(Object[] a) { return map.keySet().toArray( a ); } @Override public String toString() { return "IdentitySet{" + "map=" + map + '}'; } }

Set union and intersection


import java.util.*; /** * A utility class containing set utility functions. * * @author Oliver Steele */ public abstract class SetUtils { public static boolean containsAny(Set a, Set b) { for (Iterator iter = b.iterator(); iter.hasNext(); ) { if (a.contains(iter.next())) { return true; } } return false; } public static Set intersection(Set a, Set b) { Set c = new HashSet(); for (Iterator iter = b.iterator(); iter.hasNext(); ) { Object e = iter.next(); if (a.contains(e)) {

c.add(e); } } return c; } }

Putting your own type in a Set


import import import import java.util.HashSet; java.util.LinkedHashSet; java.util.Set; java.util.TreeSet;

public class Set2 { public static Set fill(Set a, int size) { for (int i = 0; i < size; i++) a.add(new Integer(i)); return a; } public static void test(Set a) { fill(a, 10); fill(a, 10); // Try to add duplicates fill(a, 10); a.addAll(fill(new TreeSet(), 10)); System.out.println(a); } public static void main(String[] args) { test(new HashSet()); test(new TreeSet()); test(new LinkedHashSet()); } }

Set operations
import java.util.LinkedHashSet; import java.util.Set; /** * Note: This code is based on -<br> * http://java.sun.com/docs/books/tutorial/collections/interfaces/set.html<br > * * Using LinkedHashSet, even though slightly slower than HashSet, in order to * ensure order is always respected (i.e. if called with TreeSet or

* LinkedHashSet implementations). * * @author Ravi Mohan * @author Ciaran O'Reilly */ public class SetOps { /** * * @param <T> * @param s1 * @param s2 * @return the union of s1 and s2. (The union of two sets is the set * containing all of the elements contained in either set.) */ public static <T> Set<T> union(Set<T> s1, Set<T> s2) { Set<T> union = new LinkedHashSet<T>(s1); union.addAll(s2); return union; } /** * * @param <T> * @param s1 * @param s2 * @return the intersection of s1 and s2. (The intersection of two sets is * the set containing only the elements common to both sets.) */ public static <T> Set<T> intersection(Set<T> s1, Set<T> s2) { Set<T> intersection = new LinkedHashSet<T>(s1); intersection.retainAll(s2); return intersection; } /** * * @param <T> * @param s1 * @param s2 * @return the (asymmetric) set difference of s1 and s2. (For example, the * set difference of s1 minus s2 is the set containing all of the * elements found in s1 but not in s2.) */ public static <T> Set<T> difference(Set<T> s1, Set<T> s2) { Set<T> difference = new LinkedHashSet<T>(s1); difference.removeAll(s2); return difference;

} }

Working with HashSet and TreeSet


import import import import java.util.HashSet; java.util.Iterator; java.util.Set; java.util.TreeSet;

public class ItemSet { public static void main(String args[]) { String names[] = { "Item 1", "Item 2", "Item 3"}; Set moons = new HashSet(); int namesLen = names.length; int index; for (int i = 0; i < 100; i++) { index = (int) (Math.random() * namesLen); moons.add(names[index]); } Iterator it = moons.iterator(); while (it.hasNext()) { System.out.println(it.next()); } System.out.println("---"); Set orderedMoons = new TreeSet(moons); it = orderedMoons.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }

TreeSet Demo
import java.util.TreeSet; /** * TreeSet Demo. * * @author Ian F. Darwin, http://www.darwinsys.com/ * @version $Id: TreeSetDemo.java,v 1.3 2004/02/09 03:34:04 ian Exp $ */ public class TreeSetDemo { public static void main(String[] argv) { //+ /* * A TreeSet keeps objects in sorted order. We use a Comparator * published by String for case-insensitive sorting order.

*/ TreeSet tm = new TreeSet(String.CASE_INSENSITIVE_ORDER); tm.add("Gosling"); tm.add("da Vinci"); tm.add("van Gogh"); tm.add("Java To Go"); tm.add("Vanguard"); tm.add("Darwin"); tm.add("Darwin"); // TreeSet is Set, ignores duplicates. // Since it is sorted we can ask for various subsets System.out.println("Lowest (alphabetically) is " + tm.first()); // Print how many elements are greater than "k" System.out.println(tm.tailSet("k").toArray().length + " elements higher than \"k\""); // Print the whole list in sorted order System.out.println("Sorted list:"); java.util.Iterator t = tm.iterator(); while (t.hasNext()) System.out.println(t.next()); //} }

Show the union and intersection of two sets


import java.util.*; /** Show the union and instersection of two sets. */ public class SetStuff { public static void main(String[] args) { // Create two sets. Set s1 = new HashSet(); s1.add("Ian Darwin"); s1.add("Bill Dooley"); s1.add("Jesse James"); Set s2 = new HashSet(); s2.add("Ian Darwin"); s2.add("Doolin' Dalton"); Set union = new TreeSet(s1); union.addAll(s2); // now contains the union print("union", union); Set intersect = new TreeSet(s1);

intersect.retainAll(s2); print("intersection", intersect); } protected static void print(String label, Collection c) { System.out.println("--------------" + label + "--------------"); Iterator it = c.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }

What you can do with a TreeSet


import import import import java.util.Arrays; java.util.Iterator; java.util.SortedSet; java.util.TreeSet;

public class SortedSetDemo { public static void main(String[] args) { SortedSet sortedSet = new TreeSet(Arrays .asList("one two three four five six seven eight".split(" "))); System.out.println(sortedSet); Object low = sortedSet.first(), high = sortedSet.last(); System.out.println(low); System.out.println(high); Iterator it = sortedSet.iterator(); for (int i = 0; i <= 6; i++) { if (i == 3) low = it.next(); if (i == 6) high = it.next(); else it.next(); } System.out.println(low); System.out.println(high); System.out.println(sortedSet.subSet(low, high)); System.out.println(sortedSet.headSet(high)); System.out.println(sortedSet.tailSet(low)); } }

Get Collection of Values from Java Hashtable


import import import import java.util.Collection; java.util.Enumeration; java.util.Hashtable; java.util.Iterator;

public class Main { public static void main(String[] args) { Hashtable<String, String> ht = new Hashtable<String,String>(); ht.put("1", "One"); ht.put("2", "Two"); ht.put("3", "Three"); Collection c = ht.values(); Iterator itr = c.iterator(); while (itr.hasNext()){ System.out.println(itr.next()); } c.remove("One"); Enumeration e = ht.elements(); while (e.hasMoreElements()){ System.out.println(e.nextElement()); } } }

Check if a particular key exists in Java Hashtable


import java.util.Hashtable; public class Main { public static void main(String[] args) { Hashtable<String, String> ht = new Hashtable<String, String>(); ht.put("1", "One"); ht.put("2", "Two"); ht.put("3", "Three"); boolean blnExists = ht.containsKey("2"); System.out.println("2 exists in Hashtable ? : " + blnExists); } }

Get Size of Java Hashtable

import java.util.Hashtable; public class Main { public static void main(String[] args) { Hashtable<String,String> ht = new Hashtable<String,String>(); System.out.println("Size of Hashtable : " + ht.size()); ht.put("1", "One"); ht.put("2", "Two"); ht.put("3", "Three"); System.out.println(ht.size()); Object obj = ht.remove("2"); System.out.println(ht.size()); } }

Remove all values from Java Hashtable


import java.util.Hashtable; public class Main { public static void main(String[] args) { Hashtable<String, String> ht = new Hashtable<String, String>(); ht.put("1", "One"); ht.put("2", "Two"); ht.put("3", "Three"); ht.clear(); System.out.println(ht.size()); } }

Remove value from Java Hashtable


import java.util.Enumeration; import java.util.Hashtable; public class Main { public static void main(String[] args) { Hashtable<String, String> ht = new Hashtable<String, String>(); ht.put("1", "One"); ht.put("2", "Two"); ht.put("3", "Three");

Object obj = ht.remove("2"); System.out.println(obj + " was Removed "); Enumeration e = ht.elements(); while (e.hasMoreElements()){ System.out.println(e.nextElement()); } } }

Scan the content of a hashtable


import java.util.Enumeration; import java.util.Hashtable; public class Main { public static void main(String args[]) { Hashtable<String,String> hash = new Hashtable<String,String>(); hash.put("1","one"); hash.put("2","two"); hash.put("3","three");

Enumeration keys = hash.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); Object value = hash.get(key); System.out.println(key+" : "+value); } } }

List Odd Numbers Java Example


public class ListOddNumbers { public static void main(String[] args) { //define the limit int limit = 50; System.out.println("Printing Odd numbers between 1 and " + limit);

for(int i=1; i <= limit; i++){ //if the number is not divisible by 2 then it is odd if( i % 2 != 0){ System.out.print(i + " "); } } }

Fibonacci Series Java Example


public class JavaFibonacciSeriesExample { public static void main(String[] args) { //number of elements to generate in a series int limit = 20; long[] series = new long[limit]; //create first 2 series elements series[0] = 0; series[1] = 1; //create the Fibonacci series and store it in an array for(int i=2; i < limit; i++){ series[i] = series[i-1] + series[i-2]; } //print the Fibonacci series numbers System.out.println("Fibonacci Series upto " + limit); for(int i=0; i< limit; i++){ System.out.print(series[i] + " "); } } }

Java String Array To List Example

import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Arrays; /* Java String Array To List Example This Java String Array To List Example shows how to convert Java String array to java.util.List object using Arrays.asList method. */ public class JavaStringArrayToListExample { public static void main(String args[]){ //create String array String[] numbers = new String[]{"one", "two", "three"}; /* * To covert String array to java.util.List object, use * List asList(String[] strArray) method of Arrays class. */ List list = (List) Arrays.asList(numbers); //display elements of List System.out.println("String array converted to List"); for(int i=0; i < list.size(); i++){ System.out.println(list.get(i)); } /* * Please note that list object created this way can not be modified. * Any attempt to call add or delete method would throw UnsupportedOperationException exception. * * If you want modifiable list object, then use * * ArrayList list = (ArrayList) Arrays.asList(numbers); */ /* Alternate Method to covert String array to List */

List anotherList = new ArrayList(); Collections.addAll(anotherList, numbers); }

Java Palindrome Number Example


public class JavaPalindromeNumberExample { public static void main(String[] args) { //array of numbers to be checked int numbers[] = new int[]{121,13,34,11,22,54}; //iterate through the numbers for(int i=0; i < numbers.length; i++){ int number = numbers[i]; int reversedNumber = 0; int temp=0; /* * If the number is equal to it's reversed number, then * the given number is a palindrome number. * * For example, 121 is a palindrome number while 12 is not. */ //reverse the number while(number > 0){ temp = number % 10; number = number / 10; reversedNumber = reversedNumber * 10 + temp; } if(numbers[i] == reversedNumber) System.out.println(numbers[i] + " is a palindrome number"); else System.out.println(numbers[i] + " is not a palindrome number"); }

Prime Numbers Java Example


public class GeneratePrimeNumbersExample { public static void main(String[] args) { //define limit int limit = 100; System.out.println("Prime numbers between 1 and " + limit); //loop through the numbers one by one for(int i=1; i < 100; i++){ boolean isPrime = true; //check to see if the number is prime for(int j=2; j < i ; j++){ if(i % j == 0){ isPrime = false; break; } } // print the number if(isPrime) System.out.print(i + " "); } } }