CIS 265 – Lecture Notes – Chapter21 Generics – Chapter 22 Java Collection Framework
Example 1. Set operators
packagecsu.matos;
importjava.util.HashSet;
importjava.util.Set;
publicclass Driver1 {
publicstaticvoid main(String[] args) {
// working with SET operations on ‘simple’ collections of strings
// included: Union, Difference, Intersection
Set<String> set1 = newHashSet<String>();
set1.add("ccc");
set1.add("aaa");
set1.add("bbb");
set1.add("ccc");
System.out.println(set1);
Set<String> set2 = newHashSet<String>();
set2.add("bbb");
set2.add("yyy");
System.out.println(set2);
// compute result = set1 + set2
Set<String> result;
result = newHashSet<String>(set1);
result.addAll(set2);
System.out.println("UNION " + result);
// compute result = set1 - set2
result = newHashSet<String>(set1);
result.removeAll(set2);
System.out.println("MINUS " + result);
// compute result = set1 intesection set2
result = newHashSet<String>(set1);
result.retainAll( set2 );
System.out.println("INTERSECT " + result);
}
}
Console
[aaa, ccc, bbb]
[yyy, bbb]
UNION [aaa, yyy, ccc, bbb]
MINUS [aaa, ccc]
INTERSECT [bbb]
EXAMPLE 2: Combining SETs of mixed Geometric Objects (notation: subclassing )
packagecsu.matos;
importjava.util.Set;
importjava.util.TreeSet;
publicclass Driver3 {
// Using Generics:
// Two sets of GeometricObjects (Circle and Rectangles) are combined
// The example shows the use of Comparable-Type and wild-char Types
publicstaticvoid main(String[] args) {
Set<Comparable<? extendsGeometricObject>c1 = newTreeSet<Comparable<? extendsGeometricObject> >();
c1.add(newComparableCircle(10) );
c1.add(newComparableCircle(9) );
c1.add(newComparableCircle(11) );
c1.add(newComparableCircle(2) );
System.out.println( c1 );
Set<Comparable<? extendsGeometricObject>c2 = newTreeSet<Comparable<? extendsGeometricObject> >();
c2.add(newComparableRectangle(1, 2 ) );
c2.add(newComparableRectangle(2, 2 ) );
c2.add(newComparableRectangle(2, 1 ) );
System.out.println( c2 );
Set<Comparable<? extendsGeometricObject> result = c1;
result.addAll( c2 );
System.out.println("\nAll figures including RECTANGLES and CIRCLES");
System.out.println( result );
}
}
CONSOLE
[
> Circle > Radius: 2.0 Perimeter: 12.6 Area: 12.6,
> Circle > Radius: 9.0 Perimeter: 56.5 Area: 254.5,
> Circle > Radius: 10.0 Perimeter: 62.8 Area: 314.2,
> Circle > Radius: 11.0 Perimeter: 69.1 Area: 380.1]
[
> Rectangle > Height: 2.0 Width: 1.0 Perimeter: 6.0 Area: 2.0,
> Rectangle > Height: 2.0 Width: 2.0 Perimeter: 8.0 Area: 4.0]
All figures including RECTANGLES and CIRCLES
[
> Rectangle > Height: 2.0 Width: 1.0 Perimeter: 6.0 Area: 2.0,
> Rectangle > Height: 2.0 Width: 2.0 Perimeter: 8.0 Area: 4.0,
> Circle > Radius: 2.0 Perimeter: 12.6 Area: 12.6,
> Circle > Radius: 9.0 Perimeter: 56.5 Area: 254.5,
> Circle > Radius: 10.0 Perimeter: 62.8 Area: 314.2,
> Circle > Radius: 11.0 Perimeter: 69.1 Area: 380.1]
Previous example is equivalent to:
// Using Generics:
// Two sets of GeometricObjects (Circle and Rectangles) are combined
// The example shows the use of Comparable-Type and wild-char Types
publicstaticvoid main(String[] args) {
//Set<Comparable<?extendsGeometricObject> c1 = new TreeSet<Comparable<? extendsGeometricObject>();
Set<GeometricObject> c1 = newTreeSetGeometricObject>();
c1.add(new Circle(10,"red", true));
c1.add(new Circle(9,"red", true));
c1.add(new Circle(11,"red", true));
c1.add(new Circle(2,"red", true));
System.out.println("CIRCLES\n" + c1);
//Set<Comparable<?extendsGeometricObject> c2 = new TreeSet<Comparable<? extendsGeometricObject>();
Set<GeometricObject> c2 = newTreeSetGeometricObject>();
c2.add(new Rectangle(3, 2));
c2.add(new Rectangle(2, 2));
c2.add(new Rectangle(2, 1));
System.out.println("RECTANGLES\n" + c2);
// Set<Comparable<? extendsGeometricObject> result = c1;
Set<GeometricObject> result = c1;
result.addAll(c2);
System.out.println("\nAll figures including RECTANGLES and CIRCLES");
System.out.println(result);
}
GeometricObject class
packagecsu.matos;
publicabstractclassGeometricObjectimplementsCloneable {
private String color = "white";
privatebooleanfilled;
privatejava.util.DatedateCreated;
// Construct a default geometric object
protectedGeometricObject() {
dateCreated = newjava.util.Date();
}
// createaobj with color and filled value
protectedGeometricObject(String color,
boolean filled) {
dateCreated = newjava.util.Date();
this.color = color;
this.filled = filled;
}
// Return color
public String getColor() {
returncolor;
}
// Set a new color
publicvoidsetColor(String color) {
this.color = color;
}
// Return TRUE is object is filled
publicbooleanisFilled() {
returnfilled;
}
publicvoidsetDateCreated(java.util.DatedateCreated) {
this.dateCreated = dateCreated;
}
// Set filled to either: true/false
publicvoidsetFilled(boolean filled) {
this.filled = filled;
}
// Get dateCreated
publicjava.util.DategetDateCreated() {
returndateCreated;
}
// Return a string representing this object
public String toString() {
return"created on " + dateCreated
+ "\ncolor: " + color
+ " and filled: " + filled;
}
public Object clone() throwsCloneNotSupportedException {
return super.clone();
}
// Abstract method getArea
publicabstractdoublegetArea();
// Abstract method getPerimeter
publicabstractdoublegetPerimeter();
}
Circle Class
packagecsu.matos;
importjava.text.DecimalFormat;
publicclass Circle extendsGeometricObject {
privatedoubleradius = 1;
public Circle() {
}
public Circle(double radius) {
super();
this.radius = radius;
}
public Circle(double radius, String color, boolean filled) {
super(color, filled);
this.radius = radius;
}
/** Return radius */
publicdoublegetRadius() {
returnradius;
}
/** Set a new radius */
publicvoidsetRadius(double radius) {
this.radius = radius;
}
/** Return area */
publicdoublegetArea() {
returnradius * radius * Math.PI;
}
/** Return diameter */
publicdoublegetDiameter() {
return 2 * radius;
}
/** Return perimeter */
publicdoublegetPerimeter() {
return 2 * radius * Math.PI;
}
/* Print the circle info */
publicvoidprintCircle() {
System.out.println(toString() + " Circle created on: "
+ getDateCreated() + " and the radius is " + radius);
}
public String toString() {
DecimalFormatdf = newDecimalFormat("0.0");
return"\n> Circle "
//+ "\n" + super.toString() + "\n"
+ "> Radius: " + df.format(getRadius() )
+ " \tPerimeter: "+ df.format( getPerimeter() )
+ " \tArea: " + df.format( getArea() );
}
}
ComparableCircle class
packagecsu.matos;
publicclassComparableCircleextends Circle implements Comparable<GeometricObject>{
publicComparableCircle( int radius) {
super(radius);
}
@Override
publicintcompareTo(GeometricObject otherGeometricObject ) {
if ( this.getArea() == otherGeometricObject.getArea() )
return 0;
elseif (this.getArea() > otherGeometricObject.getArea() )
return 1;
else
return -1;
}
}
Rectangle class
packagecsu.matos;
publicclass Rectangle extendsGeometricObjectimplementsCloneable {
privatedoublewidth;
privatedoubleheight;
public Rectangle() {
}
public Rectangle(double width, double height) {
super();
this.width = width;
this.height = height;
}
public Rectangle( double width,double height, String color, boolean filled) {
super(color, filled);
this.width = width;
this.height = height;
}
/** Return width */
publicdoublegetWidth() {
returnwidth;
}
/** Set a new width */
publicvoidsetWidth(double width) {
this.width = width;
}
/** Return height */
publicdoublegetHeight() {
returnheight;
}
/** Set a new height */
publicvoidsetHeight(double height) {
this.height = height;
}
/** Return area */
publicdoublegetArea() {
returnwidth * height;
}
/** Return perimeter */
publicdoublegetPerimeter() {
return 2 * (width + height);
}
public String toString() {
return"\n> Rectangle "
// + "\n" + super.toString() + "\n"
+ "> Height: " + getHeight()
+ " Width: " + getWidth()
+ " Perimeter: " + getPerimeter()
+ " Area: " + getArea();
}
@Override
// Override the protected clone method defined in the Object class
public Object clone() throwsCloneNotSupportedException {
returnsuper.clone();
}
@Override
publicboolean equals(Object obj) {
Rectangle other = (Rectangle) obj;
if ( this.getColor().equals(other.getColor() )
this.getDateCreated().equals(other.getDateCreated() )
this.getHeight() == other.getHeight()
this.getWidth() == other.getWidth() )
returntrue;
else
returnfalse;
}
}
ComparableRectangle class
packagecsu.matos;
publicclassComparableRectangleextends Rectangle implements Comparable<GeometricObject> {
// Construct a ComparableRectangle with specified properties
publicComparableRectangle(double width, double height) {
super(width, height);
}
// Implement the compareTo method defined in Comparable
publicintcompareTo(GeometricObjectobj ) {
GeometricObjectotherRectangle = (GeometricObject)obj;
if (this.getArea() > otherRectangle.getArea())
return 1;
elseif (this.getArea() < otherRectangle.getArea())
return -1;
else
return 0;
}
publicstaticComparableRectangle max( ComparableRectanglethisRectangle,
ComparableRectangleotherRectangle){
if ( thisRectangle.compareTo(otherRectangle) >= 0 )
returnthisRectangle;
else
returnotherRectangle;
}
}
Example 3: Testing SET operations on complex classes (Person) (Naive OODatabase – Part1)
packagecsu.matos;
importjava.util.Set;
importjava.util.TreeSet;
publicclass Driver2 {
// This example shows practical applications of the SET class
// when applied to a ‘complex’ type of objects.
// ------
// An "Object Oriented Data Base" model is suggested here.
// The sample sets hold instances of the Person class.
// Basic database operations are illustrated, including :
// UNION, DIFFERENCE, INTERSECTION, SELECTION, JOIN
// Examples of the PREDICATE interface are also included
// as well as a primitive RESULTSET produced by a query evaluation
// ------
publicstaticvoid main(String[] args) {
// SET1 ------
// This set contains a group of people who play BASEBALL
Set<Person> set1 = newTreeSet<Person>();
set1.add(new Person("Maria", 1111, 25));
set1.add(new Person("Charlie", 3333, 10));
set1.add(new Person("Jose", 5555, 50));
System.out.println("\n" + set1);
for (Person p : set1) {
System.out.println(p.toString());
}
// SET2 ------
// This set contains a group of people who play PING-PONG
Set<Person> set2 = newTreeSet<Person>();
set2.add(new Person("Maria", 1111, 25));
set2.add(new Person("Ivor", 7777, 10));
set2.add(new Person("Forrest", 8888, 35));
System.out.println("\n" + set2);
for (Person p : set2) {
System.out.println(p.toString());
}
Set<Person> set1Result;
// computing INTERSECTION
// Find those who play both: BASEBALL and PING-PONG
set1Result = newTreeSet<Person>(set1);
set1Result.retainAll(set2);
System.out.println("\n INTERSECTION ");
for (Person p : set1Result) {
System.out.println(p);
}
// computing UNION
// List people who play BASEBALL and/or PING-PONG
set1Result = newTreeSet<Person>(set1);
set1Result.addAll(set2);
System.out.println("\n UNION");
for (Person p : set1Result) {
System.out.println(p.toString());
}
// computing MINUS
// List those who play BASEBALL but do not play PING-PONG
set1Result = newTreeSet<Person>(set1);
set1Result.removeAll(set2);
System.out.println("\n MINUS");
for (Person p : set1Result) {
System.out.println(p.toString());
}
// /////////////////////////////////////////////////////////////////////////////////
// testing PREDICATE: oldEnough2BuyBeer
// Find those athletes who are 21 or older
System.out.println("PREDICATE");
Predicate<Person> oldEnough2BuyBeer = new Predicate<Person>() {
@Override
publicboolean test(Person p) {
if (p.getAge() >= 21)
returntrue;
else
returnfalse;
}
};// Predicate
for (Person p : set1) {
if (oldEnough2BuyBeer.test(p))
System.out.println(p.toString());
}
// /////////////////////////////////////////////////////////////////////////////////
// testing PREDICATE: nameBeginsWithM
// Find athletes whose last name begins with "M"
System.out.println("PREDICATE");
Predicate<Person> nameBeginsWithM = new Predicate<Person>() {
@Override
publicboolean test(Person p) {
char c = (p.getName().toUpperCase().charAt(0));
if (c == 'M')
returntrue;
else
returnfalse;
}
};// Predicate
for (Person p : set1) {
if (nameBeginsWithM.test(p))
System.out.println(p.toString());
}
// /////////////////////////////////////////////////////////////////////////////////
// testing RESULTSET: OldEnough2BuyBeer
// A better construction - put query results into a ResultSet
System.out.println("RESULTSET");
ResultSet<Person> query = newResultSet<Person>(oldEnough2BuyBeer, set1);
Set<Person> resultSet = query.evaluate();
for (Person p : resultSet) {
System.out.println(p.toString());
}
// /////////////////////////////////////////////////////////////////////////////////
// testing RESULTSET: evaluate query: OldEnough2BuyBeer
// take an input set and a predicate, return selected elements
// /////////////////////////////////////////////////////////////////////////////////
System.out.println("RESULTSET");
ResultSet<Person> query2 = newResultSet<Person>(nameBeginsWithM, set1);
Set<Person> resultSet2 = query2.evaluate();
for (Person p : resultSet2) {
System.out.println(p.toString());
}
// /////////////////////////////////////////////////////////////////////////////////
// testing JOIN
// combine the people in set1 with their dependents (family) listed in set3
// /////////////////////////////////////////////////////////////////////////////////
System.out.println("JOIN");
// SET3 ------
Set<Person> set3 = newTreeSet<Person>();
set3.add(new Person("Maria-Daughter1", 1111, 5));
set3.add(new Person("Maria-Son1", 1111, 7));
set3.add(new Person("Jose-Son1", 5555, 7));
for (Person p1 : set1) {
for ( Person p3 : set3 ) {
if ( p1.getId() == p3.getId() ) {
System.out.println( p1.toString() + " \t " + p3.toString() );
}
}
}
}// main
}
CONSOLE
[[ ID: 3333 Age: 10 Name: Charlie ] , [ ID: 1111 Age: 25 Name: Maria ] , [ ID: 5555 Age: 50 Name: Jose ] ]
[ ID: 3333 Age: 10 Name: Charlie ]
[ ID: 1111 Age: 25 Name: Maria ]
[ ID: 5555 Age: 50 Name: Jose ]
[[ ID: 7777 Age: 10 Name: Ivor ] , [ ID: 1111 Age: 25 Name: Maria ] , [ ID: 8888 Age: 35 Name: Forrest ] ]
[ ID: 7777 Age: 10 Name: Ivor ]
[ ID: 1111 Age: 25 Name: Maria ]
[ ID: 8888 Age: 35 Name: Forrest ]
INTERSECTION
[ ID: 1111 Age: 25 Name: Maria ]
UNION
[ ID: 7777 Age: 10 Name: Ivor ]
[ ID: 3333 Age: 10 Name: Charlie ]
[ ID: 1111 Age: 25 Name: Maria ]
[ ID: 8888 Age: 35 Name: Forrest ]
[ ID: 5555 Age: 50 Name: Jose ]
MINUS
[ ID: 3333 Age: 10 Name: Charlie ]
[ ID: 5555 Age: 50 Name: Jose ]
PREDICATE
[ ID: 1111 Age: 25 Name: Maria ]
[ ID: 5555 Age: 50 Name: Jose ]
PREDICATE
[ ID: 1111 Age: 25 Name: Maria ]
RESULTSET
[ ID: 1111 Age: 25 Name: Maria ]
[ ID: 5555 Age: 50 Name: Jose ]
RESULTSET
[ ID: 1111 Age: 25 Name: Maria ]
JOIN
[ ID: 1111 Age: 25 Name: Maria ] [ ID: 1111 Age: 5 Name: Maria-Daughter1 ]
[ ID: 1111 Age: 25 Name: Maria ] [ ID: 1111 Age: 7 Name: Maria-Son1 ]
[ ID: 5555 Age: 50 Name: Jose ] [ ID: 5555 Age: 7 Name: Jose-Son1 ]
PERSON class
packagecsu.matos;
importjava.util.Comparator;
publicclass Person implementsComparator<Person>,
Comparable<Person>,
Cloneable {
private String name;
privateintid;
privateintage;
// ------
public Person() {
name = "na";
id = -1;
age = 0;
}
public Person(String name, int id, int age) {
super();
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
returnname;
}
publicvoidsetName(String name) {
this.name = name;
}
publicintgetId() {
returnid;
}
publicvoidsetId(int id) {
this.id = id;
}
publicintgetAge() {
returnage;
}
publicvoidsetAge(int age) {
this.age = age;
}
// ------
public String toString() {
String result = "[ ID: " + id + " Age: " + age + " Name: " + name
+ " ] ";
return result;
}
// ------
@Override
publicintcompareTo(Person person2) {
// ordering according to age values
if (this.getAge() == person2.getAge()
this.getId() == person2.getId()
this.getName().compareTo(person2.getName()) == 0)
return 0;
elseif (this.getAge() > person2.getAge())
return 1;
else
return -1;
}
// ------
@Override
publicint compare(Person person1, Person person2) {
// ordering according to age values
if (person1.getAge() == person2.getAge())
return 0;
elseif (person1.getAge() > person2.getAge())
return 1;
else
return -1;
}
// ------
@Override
publicboolean equals(Object objPerson) {
try{
Person other = (Person)objPerson;
if ( this.name.equals(other.name)
this.id == other.id
this.age == other.age)
returntrue;
else
returnfalse;
}catch (Exception e){
returnfalse;
}
}
// ------
@Override
protected Object clone() throwsCloneNotSupportedException {
returnsuper.clone();
}
// ------
}
Predicate Interface
packagecsu.matos;
publicinterface Predicate <E> {
publicboolean test(E obj);
}
ResultSet class
packagecsu.matos;
importjava.util.Set;
importjava.util.TreeSet;
publicclassResultSet <E> {
Predicate<E> predicate;
Set<E> set;
// ////////////////////////////////////////////////////////////////
publicResultSet() {
}
publicResultSet(Predicate<E> predicate, Set<E> set) {
this.predicate = predicate;
this.set = set;
}
// ////////////////////////////////////////////////////////////////
public Set<E> evaluate ( ){
Set<E> result = newTreeSet<E>();
for (E element : set ){
if ( predicate.test( element ) )
result.add( element );
}
return result;
}
}
EXAMPLE4: Using ArrayLists and Maps to Create Multiple Indices (Baby OO Database – Part 2)
packagecsu.matos;
importjava.util.ArrayList;
publicclass Driver3 {
/**************************************************************
* Baby OODatabase
* Using ArrayList to hold Person(name, id, age) objects .
* Indices implemented as TreeMaps: idMap, nameMap, ageMap
**************************************************************/
publicstaticvoid main(String[] args) {
// define Object Oriented Person Database
OODB db = newOODB();
// add Person to database, update indices ------
db.dbAdd(new Person("Ender Wiggin", 222, 12));
db.dbAdd(new Person("Miles Vorkosigan", 444, 25));
db.dbAdd(new Person("Honor Harrington", 111, 28));
db.dbAdd(new Person("Alvin Maker", 333, 10));
db.dbAdd(new Person("R. DaneelOlivaw", 555, 30));
db.dbAdd(new Person("CerseiLannister", 666, 34));
db.dbAdd(new Person("Arya Stark", 888, 12));
db.dbAdd(new Person("DaenerysTargaryen", 999, 18));
// show database entries ------
System.out.println("PERSON LIST\n" + db.getList() + "\n");
for(inti=0; idb.getList().size(); i++){
Person p = db.getList().get(i);
System.out.println(i + p.toString());
}
// show database indices
System.out.println ("idMap \t" + db.getIdMap() );
System.out.println ("nameMap \t" + db.getNameMap() );
System.out.println ("ageMap \t" + db.getAgeMap() );
// retrieve by NAME ------
System.out.println("\nRetrieving by NAME ");
Integer position = null;
String nameKey = "Arya Stark";
position = db.getNameMap().get(nameKey);
if (position != null){
System.out.println(" Using nameMap (" + nameKey + "):\t "
+ position
+ db.getList().get(position));
}
// retrieve by ID ------
System.out.println("\nRetrieving by ID ");
intidKey = 555;
position = db.getIdMap().get(idKey);
if (position != null)
System.out.println(" Using idMap key (" + idKey + ")\t "
+ position
+ db.getList().get(position));
else
System.out.println("\nidkey not in Index (" + idKey + ")");
// ------
// retrieve by AGE (expect multiple values for a key)
intageKey = 12;
System.out.println("\nRetrieving by AGE "
+ db.getAgeMap().get(ageKey));
ArrayList<Integer> peopleSameAge = db.getAgeMap().get(ageKey);
for (Integer pos : peopleSameAge) {
if (pos != null){
System.out.println(" Using ageMap key (" + ageKey + ")\t "
+ pos
+ db.getList().get(pos));
}
}
// ------
// ordered retrieval according to ID values
System.out.println( "\nNavigation using idMap - Listing People in ID order");
Integer key = db.getIdMap().firstKey();
while ( key != null ){
position = db.getIdMap().get(key);
System.out.println( " Key: " + key + " Value: "
+ position
+ "\t" + db.getList().get(position) );
key = db.getIdMap().higherKey(key);
}
}// main
}
CONSOLE
PERSON LIST
[[ ID: 222 Age: 12 Name: Ender Wiggin ] , [ ID: 444 Age: 25 Name: Miles Vorkosigan ] ,
[ ID: 111 Age: 28 Name: Honor Harrington ] , [ ID: 333 Age: 10 Name: Alvin Maker ] ,
[ ID: 555 Age: 30 Name: R. DaneelOlivaw ] , [ ID: 666 Age: 34 Name: CerseiLannister ] ,
[ ID: 888 Age: 12 Name: Arya Stark ] , [ ID: 999 Age: 18 Name: DaenerysTargaryen ] ]
0[ ID: 222 Age: 12 Name: Ender Wiggin ]
1[ ID: 444 Age: 25 Name: Miles Vorkosigan ]
2[ ID: 111 Age: 28 Name: Honor Harrington ]
3[ ID: 333 Age: 10 Name: Alvin Maker ]
4[ ID: 555 Age: 30 Name: R. DaneelOlivaw ]
5[ ID: 666 Age: 34 Name: CerseiLannister ]
6[ ID: 888 Age: 12 Name: Arya Stark ]
7[ ID: 999 Age: 18 Name: DaenerysTargaryen ]
idMap {111=2, 222=0, 333=3, 444=1, 555=4, 666=5, 888=6, 999=7}
nameMap{Alvin Maker=3, Arya Stark=6, CerseiLannister=5, DaenerysTargaryen=7, Ender Wiggin=0,
Honor Harrington=2, Miles Vorkosigan=1, R. DaneelOlivaw=4}
ageMap {10=[3], 12=[0, 6], 18=[7], 25=[1], 28=[2], 30=[4], 34=[5]}
Retrieving by NAME
Using nameMap (Arya Stark): 6[ ID: 888 Age: 12 Name: Arya Stark ]
Retrieving by ID
Using idMap key (555) 4[ ID: 555 Age: 30 Name: R. DaneelOlivaw ]
Retrieving by AGE [0, 6]
Using ageMap key (12) 0[ ID: 222 Age: 12 Name: Ender Wiggin ]
Using ageMap key (12) 6[ ID: 888 Age: 12 Name: Arya Stark ]
Navigation using idMap - Listing People in ID order
Key: 111 Value: 2[ ID: 111 Age: 28 Name: Honor Harrington ]
Key: 222 Value: 0[ ID: 222 Age: 12 Name: Ender Wiggin ]
Key: 333 Value: 3[ ID: 333 Age: 10 Name: Alvin Maker ]
Key: 444 Value: 1[ ID: 444 Age: 25 Name: Miles Vorkosigan ]
Key: 555 Value: 4[ ID: 555 Age: 30 Name: R. DaneelOlivaw ]
Key: 666 Value: 5[ ID: 666 Age: 34 Name: CerseiLannister ]
Key: 888 Value: 6[ ID: 888 Age: 12 Name: Arya Stark ]
Key: 999 Value: 7[ ID: 999 Age: 18 Name: DaenerysTargaryen ]
EVEN NUMBERED PROBLEMS
Exercise22_2 - displaying a list of non-duplicated words in ascending order
packagecsu.matos;
importjava.util.*;
import java.io.*;
// displaying non-duplicated words in ascending order
publicclass Exercise22_2 {
publicstaticvoid main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java Exercise22_2 fullfilename");
System.exit(0);
}
String filename = args[0];
// Create a tree set to hold the words
TreeSet<String> treeSet = newTreeSet<String>();
try {
Scanner in = newScanner(new File(filename));
String line;
while ((line = in.nextLine()) != null) {
System.out.println( line );
String[] tokens = line.split("[ |\n|\t|\r|.|,|)|(|-|\"]");
for (inti = 0; itokens.length; i++)
treeSet.add(tokens[i]);
}
} catch (Exception ex) {
System.err.println("DONE ");
}
// Get an iterator for the set
Iteratoriterator = treeSet.iterator();
// Display mappings
System.out.println("\nDisplay words in ascending order ");
while (iterator.hasNext()) {
String key = (String) iterator.next();
System.out.println(key);
}
}
}
CONSOLE
Now is the time for all good men
to come to the aid of their country
DONE
Display words in ascending order
Now
aid
all
come
country
for
good
is
men
of
the
their
time
to
A variation of Exercise22_2. - displaying the count of non-duplicated words in ascending order
packagecsu.matos;
importjava.util.*;
import java.io.*;
// displaying the count of non-duplicated words in ascending order
publicclass Exercise22_2B{
publicstaticvoid main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java Exercise22_2B fullfilename");
System.exit(0);
}
String filename = args[0];
// Create a treeset & a map to hold the words
TreeMap<String, Integer> treeMap = newTreeMap<String, Integer>();
String key = "";
Integer value = 0;;
try {
Scanner in = newScanner(new File(filename));
String line;
while ((line = in.nextLine()) != null) {
String[] tokens = line.split("[ |\n|\t|\r|.|,|\'|)|(|-|\"]");
for (inti = 0; itokens.length; i++) {
key = tokens[i];
if ( treeMap.containsKey(key) ){
value = treeMap.get(key);
treeMap.put(key, ++value);
}
else {
treeMap.put(key, 1);
}
}//for
}
} catch (Exception ex) {
System.err.println(ex);
}
// Display mappings
System.out.println("\nDisplay words in ascending order ");
System.out.println(treeMap );
key = treeMap.firstKey();
while ( key != null ){
value = treeMap.get(key);
System.out.println(value +"\t" + key);
key = treeMap.higherKey(key);
}
}
}
CONSOLE
Display words in ascending order
{Now=1, aid=1, all=1, come=1, country=1, for=1, good=1, is=1, men=1, of=1, the=2, their=1, time=1, to=2}
1Now
1aid
1all
1come
1country
1for
1good
1is
1men
1of
2the
1their
1time
2to
Exercise 22_6 (Console Version) - Using COLLECTIONS class methods (sort, shuffle, …)