0% found this document useful (0 votes)
18 views5 pages

JP-II Lab5

This document provides an introduction to using Java collections including Lists, Sets, and Maps. It includes code examples and exercises to practice using these collections to store and retrieve data. The exercises guide students to explore different collection types and their capabilities.

Uploaded by

Hồng Quân
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views5 pages

JP-II Lab5

This document provides an introduction to using Java collections including Lists, Sets, and Maps. It includes code examples and exercises to practice using these collections to store and retrieve data. The exercises guide students to explore different collection types and their capabilities.

Uploaded by

Hồng Quân
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

JP-II-Lab5 – java.

util and Collections API (Part 1)

JAVA PROGRAMMING II
Module 5: java.util and Collections API (Part1)
Lab Guide for Lab5

Session Objectives
In this session, you will be practicing with Java Collection API for managing group of
objects, includes:
⮚ Introduction to java.util Packages

⮚ Lists, ArrayList, LinkedList

⮚ Set

⮚ Map

Part 1 – Getting started (30 minutes)


Exercise 1: Using List (5 minutes).

The following program uses ArrayList to store the String objects, so we can use some
useful methods such as add() contains() or indexOf(). We also use Collections.sort() to
sort a List.
Scan the code first, copy/paste the code, compile, run , observe the result and discuss with your
classmate or instructor.

File: LyricWord.java
import java.util.*;

public class LyricWord {


private static final String[] lyric = {"you", "say", "it", "best",
"when", "you", "say", "nothing", "at", "all"};

public static void main(String[] args) {


// Create a list that’s implemented by ArrayList
List words = new ArrayList();
// Add all String in string array to list
for (String w : lyric)
words.add(w);

© FPT-Aptech Page 1 / 5
JP-II-Lab5 – java.util and Collections API (Part 1)

// Traverse the list


for (Object o : words)
System.out.print(o + " ");
System.out.println("\n------------------");

System.out.println("Contains [you]?:" + words.contains("you"));


System.out.println("Contains [me]?:" + words.contains("me"));
System.out.println("Where's [say]?:" + words.indexOf("say"));
System.out.println("Where's the last [say]?: " +
words.lastIndexOf("say"));

//Sort words
Collections.sort(words);

//show all elements of words


for (Object o : words) {
System.out.print(o + " ");
}
}
}

Exercise 2: Using Set (10 minutes).

The following program uses HashSet to store the String objects, so we can use some
useful methods such as add() contains() to add an element to set and check if it is in.
Scan the code first, copy/paste the code, compile, run , observe the result and discuss with your
classmate or instructor.

File: LyricSet.java
import java.util.*;

public class LyricSet {


private static final String[] lyric = {"you", "say", "it", "best",
"when", "you", "say", "nothing", "at", "all"};

public static void main(String[] args) {


// Create a set from HashSet that’s implemented Set
Set words = new HashSet();
// Add all words to set
for (String w : lyric)
words.add(w);

// Traverse the list


// NOTICE: set doesn't allow duplicate items

© FPT-Aptech Page 2 / 5
JP-II-Lab5 – java.util and Collections API (Part 1)

for (Object o : words)


System.out.print(o + " ");
System.out.println("\n------------------");

System.out.println("Contains [you]?:" + words.contains("you"));


System.out.println("Contains [me]?:" + words.contains("me"));
}
}

Perform following steps and answer these questions:


1. Compile, run file and observe result, compare with LyricList example above.
2. Replace HashSet by LinkedHashSet or TreeSet. Find the differences.
- ở HashSet và TreeSet các phần tử sẽ được sắp xếp lại và phần tử trùng lặp sẽ bị
loại bỏ
- ở LinkedHashSet các phần tử trùng lặp sẽ bị loại bỏ nhưng không được sắp xếp
3. Note that Set is unordered, find the way to get an index of an element in Set.

Exercise 3: Using Map (15 minutes)

The following program uses HashMap to store the information about the planets, each
planet is described by a unique name so we can access it easily.
Scan the code first, copy/paste the code, compile, run , observe the result and discuss with your
classmate or instructor.

File: PlanetDiameters.java
import java.util.*;

public class PlanetDiameters {


//array of planets’ name
private static final String[] names = {"Mercury", "Venus", "Earth",
"Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto" };

//Array of planets’ diameter


private static final float[] diameters = { 4800f, 12103.6f,
12756.3f, 6794f, 142984f, 120536f, 51118f, 49532f, 2274f };

public static void main(String[] args) {


//Use Map to store planets’ names and their corresponding
//diameters.
Map planets = new HashMap();

// Add items (key , value) to the map


for (int i = 0; i < names.length; i++)
planets.put(names[i], diameters[i]);

© FPT-Aptech Page 3 / 5
JP-II-Lab5 – java.util and Collections API (Part 1)

// Traverse the map


Iterator it = planets.entrySet().iterator();
while (it.hasNext()) {
Map.Entry e = (Map.Entry) it.next();
System.out.println(e.getKey() + ": " + e.getValue());
}
System.out.println("--------------------");

// Find a planet by name basing on key


while (true) {
System.out.print("Find planet (ENTER to quit): ");
String name = (new Scanner(System.in)).nextLine();
if (name.length() == 0) break;

if (!planets.containsKey(name))
System.out.println("Planet " + name + " not found!");
else
System.out.println("The diameter of " + name +
" is " + planets.get(name));
}
}
}

Perform following steps and answer these questions:


1. Compile, run file and observe results.
2. Replace HashMap by LinkedHashMap or TreeMap. Find the differences.

Part 2 – Workshops (30 minutes)

● Quickly look at workshops of Module 5 for reviewing basic steps for creating and using
collections in specific cases.
● Try to compile, run and observe the output of sample code provided for related
workshops. Discuss with your class-mate and your instructor if needed.

Part 3 – Lab Assignment (60 minutes)

Do the assignment for Module 5 carefully. Discuss with your class-mates and your instructor
if needed.

© FPT-Aptech Page 4 / 5
JP-II-Lab5 – java.util and Collections API (Part 1)

Part 4 – Do it yourself

Exercise 1:

Using the Collections Framework, write a Student Management program that has the
following functional menu:
1. Add Students
2. Update a Student
3. Delete a Student
4. Search Students
5. Display All Students
6. Save to File
7. Load from File
8. Exit
Your choice: _

For each student, the program should maintain RollNumber, Name, Age, and Mark.

Try to use some collection types such as List, Map, Set and compare these solutions.
Then find the best way to solve this problem.

© FPT-Aptech Page 5 / 5

You might also like