0% found this document useful (0 votes)
10 views

Exercises 4 1

The document contains solutions to 7 Java programming exercises involving collections and their methods. The exercises cover creating and printing lists, sets, and maps; adding elements and handling duplicates; autoboxing and unboxing; reversing and sorting collections; and creating a map of Person objects with Swedish personal numbers as keys. The expected output is provided for each exercise.

Uploaded by

amitha sanjaa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Exercises 4 1

The document contains solutions to 7 Java programming exercises involving collections and their methods. The exercises cover creating and printing lists, sets, and maps; adding elements and handling duplicates; autoboxing and unboxing; reversing and sorting collections; and creating a map of Person objects with Swedish personal numbers as keys. The expected output is provided for each exercise.

Uploaded by

amitha sanjaa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

exercises-1.

md 2023-11-23

Exercise 1a: Creating Lists

Description: Write a Java program that creates an ArrayList of integers, adds some elements to it,
and prints the contents of the list.

Expected Console Output:

ArrayList: [10, 20, 30, 40, 50]

1 / 22
exercises-1.md 2023-11-23

Solution:

import java.util.ArrayList;

public class ArrayListExample {


public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
numbers.add(50);

System.out.println("ArrayList: " + numbers);


}
}

2 / 22
exercises-1.md 2023-11-23

Exercise 1b: Creating Lists

Description: Write a Java program that creates an immutable List of integers using List.of(), and
prints the contents of the list.

Expected Console Output:

List: [10, 20, 30, 40, 50]

3 / 22
exercises-1.md 2023-11-23

Solution:

import java.util.List;

public class ImmutableListExample {


public static void main(String[] args) {
List<Integer> numbers = List.of(10, 20, 30, 40, 50);

System.out.println("List: " + numbers);


}
}

4 / 22
exercises-1.md 2023-11-23

Exercise 2: Working with Sets

Description: Create a HashSet of strings. Add several duplicate values to the set and observe how
duplicates are handled. Print the final set.

Expected Console Output:

HashSet: [apple, banana, cherry, grape, orange]

5 / 22
exercises-1.md 2023-11-23

Solution:

import java.util.HashSet;

public class HashSetExample {


public static void main(String[] args) {
HashSet<String> fruits = new HashSet<>();
fruits.add("apple");
fruits.add("banana");
fruits.add("cherry");
fruits.add("grape");
fruits.add("orange");

// Adding duplicates
fruits.add("apple");
fruits.add("grape");

System.out.println("HashSet: " + fruits);


}
}

6 / 22
exercises-1.md 2023-11-23

Exercise 3: Creating Maps

Description: Write a program that creates an immutable HashMap where the keys are names
(strings) and the values are ages (integers) using Map.of(). Add several key-value pairs and print the
contents of the map.

Expected Console Output:

HashMap: {Alice=25, Bob=30, Carol=28, Dave=22}

7 / 22
exercises-1.md 2023-11-23

Solution:

import java.util.Map;

public class ImmutableMapExample {


public static void main(String[] args) {
Map<String, Integer> ageMap = Map.of(
"Alice", 25,
"Bob", 30,
"Carol", 28,
"Dave", 22
);

System.out.println("HashMap: " + ageMap);


}
}

8 / 22
exercises-1.md 2023-11-23

Exercise 4: Type Wrappers

Description: Create an ArrayList of Integer objects and demonstrate autoboxing and unboxing by
first adding integers and then adding all values in the list.

Expected Console Output:

150

9 / 22
exercises-1.md 2023-11-23

Solution:

import java.util.ArrayList;
import java.util.List;

public class AutoboxingExample {


public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
numbers.add(50);

int sum = 0;
for (int n : numbers) {
sum += n;
}
System.out.println(sum);
}
}

10 / 22
exercises-1.md 2023-11-23

Exercise 5: Traversing Collections

Description: Write a function that takes an ArrayList of strings as input and prints each element in
reverse order, one per line. Each word should be reversed as well as the list.

Expected Console Output:

oof
olleh
dlrow

Hints: Collections.reverse() and StringBuilder.reverse()

11 / 22
exercises-1.md 2023-11-23

Solution:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ReverseArrayList {


public static void main(String[] args) {
List<String> words = new ArrayList<>();
words.add("world");
words.add("hello");
words.add("foo");

printReversed(words);
}

public static void printReversed(List<String> list) {


Collections.reverse(list);
for (String word : list) {
System.out.println(new StringBuilder(word).reverse());
}
}
}

12 / 22
exercises-1.md 2023-11-23

Exercise 6: Sorting Collections

Description: Create an ArrayList of objects representing products with names and prices. Implement
a comparator to sort the list by price in ascending order.

Expected Console Output:

Sorted Products:
Product[name=Monitor, price=200.0]
Product[name=Phone, price=500.0]
Product[name=Laptop, price=800.0]

13 / 22
exercises-1.md 2023-11-23

Solution:

import java.util.ArrayList;
import java.util.List;

record Product (String name, double price) {}

public class ProductSorting {


public static void main(String[] args) {
List<Product> products = new ArrayList<>();
products.add(new Product("Laptop", 800.0));
products.add(new Product("Phone", 500.0));
products.add(new Product("Monitor", 200.0));

// Sort by price in ascending order


products.sort((p1, p2) -> p1.price() < p2.price() ? -1 :
p1.price() > p2.price() ? 1 : 0);
// or products.sort((p1, p2) -> Double.compare(p1.price(),
p2.price()));
// or products.sort(Comparator.comparingDouble(Product::price));

System.out.println("Sorted Products:");
for (Product product : products) {
System.out.println(product);
}
}
}

14 / 22
exercises-1.md 2023-11-23

Exercise 7: Map of Persons with Swedish Personal Numbers

Description: Create a taxBase map that represents a Swedish tax database, where each person is
associated with their unique Swedish personal number (personnummer). The taxBase map should
have personal numbers (in the format "YYYYMMDD-XXXX") as keys and Person objects as values.
Each Person object should be a record with fields pnumber (personal number as a string), name, and
income. Populate the taxBase map using Map.of with four Person objects.

Implement the following actions:

1. Fetch a person using an existing Swedish personal number and display their information if
found.
2. Attempt to fetch a person using a non-existent Swedish personal number and handle the case
when the person is not found using a null check.

Expected Console Output (Existing Personal Number):

Person found with personal number '19850214-5678':


Person[pnumber=19850214-5678, name=Lasse, income=60000.0]

Expected Console Output (Non-Existent Personal Number):

Person with personal number '20001122-7890' not found.

15 / 22
exercises-1.md 2023-11-23

Solution:

import java.util.Map;

record Person(String pnumber, String name, double income) {}

public class TaxBaseExample {


public static void main(String[] args) {
Map<String, Person> taxBase = Map.of(
"19900101-1234", new Person("19900101-1234", "Kalle",
50000.0),
"19850214-5678", new Person("19850214-5678", "Lasse",
60000.0),
"19780325-4321", new Person("19780325-4321", "Nisse",
75000.0),
"19930630-9876", new Person("19930630-9876", "Lisa", 45000.0)
);

// Fetch a person using an existing personal number


String existingPNumber = "19850214-5678";
Person existingPerson = taxBase.get(existingPNumber);
if (existingPerson != null) {
System.out.println("Person found with personal number '" +
existingPNumber + "': " + existingPerson);
} else {
System.out.println("Person with personal number '" +
existingPNumber + "' not found.");
}

// Fetch a person using a non-existent personal number


String nonExistentPNumber = "20001122-7890";
Person nonExistentPerson = taxBase.get(nonExistentPNumber);
if (nonExistentPerson != null) {
System.out.println("Person found with personal number '" +
nonExistentPNumber + "': " + nonExistentPerson);
} else {
System.out.println("Person with personal number '" +
nonExistentPNumber + "' not found.");
}
}
}

16 / 22
exercises-1.md 2023-11-23

Exercise 8: Using LinkedHashSet

Description: Create a LinkedHashSet of characters and add some characters to it. Demonstrate how
the order of insertion is preserved when iterating over the set.

Expected Console Output:

LinkedHashSet: [A, B, C, D, E]

17 / 22
exercises-1.md 2023-11-23

Solution:

import java.util.LinkedHashSet;
import java.util.Set;

public class LinkedHashSetExample {


public static void main(String[] args) {
Set<Character> characters = new LinkedHashSet<>();
characters.add('A');
characters.add('B');
characters.add('C');
characters.add('D');
characters.add('E');

System.out.println("LinkedHashSet: " + characters);


}
}

18 / 22
exercises-1.md 2023-11-23

Exercise 9: TreeMap

Description: Create a TreeMap where the keys are integers and the values are strings. Add key-value
pairs and then print the map in ascending order of keys.

Expected Console Output:

TreeMap:
1: One
2: Two
3: Three
4: Four

19 / 22
exercises-1.md 2023-11-23

Solution:

import java.util.Map;
import java.util.TreeMap;

public class TreeMapExample {


public static void main(String[] args) {
Map<Integer, String> treeMap = new TreeMap<>();
treeMap.put(2, "Two");
treeMap.put(1, "One");
treeMap.put(4, "Four");
treeMap.put(3, "Three");

System.out.println("TreeMap:");
for (Map.Entry<Integer, String> entry : treeMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}

20 / 22
exercises-1.md 2023-11-23

Exercise 10: Custom Objects in Sets

Description: Define a record Student with attributes name and roll number. Override the equals and
hashCode methods to only use the roll number when comparing and calculating a hashCode. Create
a HashSet of Student objects and demonstrate how to add, and iterate over the set. Show how the
set will refuse more than one student with a particular roll number.

Expected Console Output:

Students:
Student[name='Alice', rollNumber=101]
Student[name='Bob', rollNumber=102]
Student[name='Carol', rollNumber=103]

Hint: Use Objects.hash() to calculate the hash code.

21 / 22
exercises-1.md 2023-11-23

Solution:

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

record Student(String name, int rollNumber) {


@Override
public boolean equals(Object o) {
return o instanceof Student s && rollNumber == s.rollNumber;
}

@Override
public int hashCode() {
return Objects.hash(rollNumber);
}
}

public class StudentHashSet {


public static void main(String[] args) {
Set<Student> students = new HashSet<>();
students.add(new Student("Alice", 101));
students.add(new Student("Bob", 102));
students.add(new Student("Carol", 103));
students.add(new Student("Caroll", 103));

System.out.println("Students:");
for (Student student : students) {
System.out.println(student);
}
}
}

22 / 22

You might also like