Java Collections Basics: Arrays, Lists, Strings, Sets, Maps

advertisement
Java Collections
Arrays, Lists, Strings, Sets, Maps
SoftUni Team
Technical Trainers
Software University
http://softuni.bg
Table of Contents
1. Arrays

int[], String[], etc.
2. Lists

ArrayList<E>
3. Strings

String str = "Hello";
4. Sets

HashSet<E>, TreeSet<E>
5. Maps

HashMap<K, V>, TreeMap<K, V>
2
Warning: Not for Absolute Beginners
 The "Java Fundamentals" course is NOT for absolute beginners
 Take the "C# Basics" course at SoftUni first:
https://softuni.bg/courses/csharp-basics
 The course is for beginners, but with previous coding skills
 Requirements
 Coding skills – entry level
 Computer English – entry level
 Logical thinking
3
Arrays
What are Arrays?
 In programming array is a sequence of elements
 All elements are of the same type
 The order of the elements is fixed
 Has fixed size (length)
Array of 5 elements
0
…
1
…
2
…
3
…
4
…
Element index
Element
of an array
5
How arrays are stored in the memory
 Reference data type
 Variable “classmates” holds
addresses in the heap as values.
 Each address points to a
separate value in the heap
memory.
6
Working with Arrays in Java
 Allocating an array of 10 integers:
int[] numbers = new int[10];
 Assigning values to the array elements:
for (int i=0; i<numbers.length; i++)
numbers[i] = i+1;
 Accessing array elements by index:
numbers[3] = 20;
numbers[5] = numbers[2] + numbers[7];
7
Arrays of Strings
 You may define an array of any type, e.g. String:
String[] names = { "Peter", "Maria", "Katya", "Todor" };
for (int i = 0; i<names.length; i++) {
System.out.printf("names[%d] = %s\n", i, names[i]);
}
for (String name : names) {
System.out.println(name);
}
names[4] = "Nakov"; // ArrayIndexOutOfBoundsException
names.length = 5; // array.length is read-only field
8
Read, Sort and Print Array of n Strings
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine();
String[] lines = new String[n];
for (int i = 0; i < n; i++) {
lines[i] = scanner.nextLine();
}
Arrays.sort(lines);
for (int i = 0; i < lines.length; i++) {
System.out.println(lines[i]);
}
9
Arrays
Live Demo
Lists
Using ArrayList<E>
Lists in Java
 In Java arrays have fixed length
 Cannot add / remove / insert elements
 Lists are like resizable arrays
 Allow add / remove / insert of elements
 Lists in Java are defined through the ArrayList<E> class
 Where E is the type of the list, e.g. String or Integer
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
System.out.println(numbers.get(0)); // 5
12
How array lists are stored in the memory
 Reference data type
 Variable “ages” holds pointers
to Objects in the heap as values.
 Each Object has an address that
points to a value in the memory.
 Future reference
 Arrays vs ArrayLists
13
ArrayList<String> – Example
ArrayList<String> names = new ArrayList<String>() {{
add("Peter");
add("Maria");
add("Katya");
add("Todor");
}};
names.add("Nakov"); // Peter, Maria, Katya, Todor, Nakov
names.remove(0); // Maria, Katya, Todor, Nakov
names.remove(1); // Maria, Todor, Nakov
names.remove("Todor"); // Maria, Nakov
names.addAll(Arrays.asList("Alice", "Tedy"));
// Maria, Nakov, Alice, Tedy
names.add(3, "Sylvia"); // Maria, Nakov, Alice, Sylvia, Tedy
names.set(2, "Mike"); // Maria, Nakov, Mike, Sylvia, Tedy
System.out.println(names);
14
ArrayList<Integer> – Example
// This will not compile!
ArrayList<int> intArr = new ArrayList<int>();
ArrayList<Integer> nums = new ArrayList<>(
Arrays.asList(5, -3, 10, 25));
nums.add(55); // 5, -3, 10, 25, 55
System.out.println(nums.get(0)); // 5
System.out.println(nums); // [5, -3, 10, 25, 55]
nums.remove(2); // 5, -3, 25, 55
nums.set(0, 101); // 101, -3, 25, 55
System.out.println(nums); // [101, -3, 25, 55]
15
ArrayList<E>
Live Demo
Strings
Basic String Operations
What Is String?
 Strings are indexed sequences of Unicode characters
 Represented by the String class in Java
 Characters accessed by index: 0 … length()-1
 Example:
string s = "Hello, SoftUni!";
s
H e l l o ,
0
1
2
3
4
5
S o f t U n i !
6
7
8
9
10 11 12 13 14
18
Working with Strings
 Strings in Java
 Know their number of characters: length()
 Can be accessed by index: charAt(0 … length()-1)
 Reference types
 Stored in the heap (dynamic memory)
 Can have null value (missing value)
 Strings cannot be modified (immutable)
 Most string operations return a new String instance
 StringBuilder class is used to build stings
19
Strings – Examples
String str = "SoftUni";
System.out.println(str);
for (int i = 0; i < str.length(); i++) {
System.out.printf("str[%d] = %s\n", i, str.charAt(i));
}
System.out.println(str.indexOf("Uni")); // 4
System.out.println(str.indexOf("uni")); // -1 (not found)
System.out.println(str.substring(4, 7)); // Uni
System.out.println(str.replace("Soft", "Hard")); // HardUni
System.out.println(str.toLowerCase()); // softuni
System.out.println(str.toUpperCase()); // SOFTUNI
20
Strings – Examples (2)
String firstName = "Steve";
String lastName = "Jobs";
int age = 56;
System.out.println(firstName + " " + lastName +
" (age: " + age + ")"); // Steve Jobs (age: 56)
String allLangs = "C#, Java; HTML, CSS; PHP, SQL";
String[] langs = allLangs.split("[, ;]+");
for (String lang : langs) {
System.out.println(lang);
}
System.out.println("Langs = " + String.join(", ", langs));
System.out.println(" \n\n Software
University ".trim());
21
Comparing Strings in Java
 The == operator does not work correctly for strings!

Use String.equals(String) and String.compareTo(String)
String[] words = "yes yes".split(" ");
System.out.println("words[0] = " + words[0]); // yes
System.out.println("words[1] = " + words[0]); // yes
System.out.println(words[0] == words[1]); // false
System.out.println(words[0].equals(words[1])); // true
System.out.println("Alice".compareTo("Mike")); // < 0
System.out.println("Alice".compareTo("Alice")); // == 0
System.out.println("Mike".compareTo("Alice")); // > 0
22
Strings
Live Demos
Sets
HashSet<E> and TreeSet<E>
Sets in Java
 Sets in Java keep unique elements
 Like lists but duplicated elements are stored only once
 HashSet<E>
 Keeps a set of elements in a hash-tables
 The elements are randomly ordered (by their hash code)
 TreeSet<E>
 Keeps a set of elements in a red-black ordered search tree
 The elements are ordered incrementally
25
How hash sets are stored in the memory
 Reference data type

Variable “names” holds hash
indexes that point to Objects in
the heap as values.

Each Object has an address that
points to a value in the memory.
 Future Reference

HashSet

TreeSet
26
HashSet<E> and TreeSet<E> – Examples
Set<String> set = new TreeSet<String>();
set.add("Pesho");
set.add("Tosho");
set.add("Pesho");
set.add("Gosho");
set.add("Maria");
set.add("Alice");
set.remove("Pesho");
System.out.println(set); // [Alice, Gosho, Maria, Tosho]
27
Maps
Maps in Java
 Maps in Java keep unique <key, value> pairs
 HashMap<K, V>
 Keeps a map of elements in a hash-table
 The elements are randomly ordered (by their hash code)
 TreeMap<K, V>
 Keeps a set of elements in a red-black ordered search tree
 The elements are ordered incrementally by their key
29
How hash maps are stored in the memory
 Reference data type
 Variable “phonebook” holds
hash indexes that point to keys
in the heap as values.
 Each key points to a value in
the memory.
30
HashMap<K, V> – Examples
 Counting words occurrences in a list:
String[] words = { "yes", "hi", "hello", "hi", "welcome",
"yes", "yes", "welcome", "hi", "yes", "hello", "yes" };
Map<String, Integer> wordsCount = new HashMap<String, Integer>();
for (String word : words) {
Integer count = wordsCount.get(word);
if (count == null) {
count = 0;
}
wordsCount.put(word, count+1);
}
System.out.println(wordsCount); // {hi=3, yes=5, hello=2, welcome=2}
31
TreeMap<K, V> – Examples
 Students and their grades
HashMap<String, ArrayList<Integer>> grades = new HashMap<>();
grades.put("Peter", new ArrayList<>(Arrays.asList(5)));
grades.put("George", new ArrayList<>(Arrays.asList(5, 5, 6)));
grades.put("Maria", new ArrayList<>(Arrays.asList(5, 4, 4)));
grades.get("Peter").add(6);
grades.get("George").add(6);
for (String key : grades.keySet()) {
System.out.println("" + key + " -> " + grades.get(key));
}
32
Future References
 Java Oracle documentation http://docs.oracle.com/javase/tutorial/collections/index.html
 The book “Java Generics and Collections” http://www.amazon.com/dp/0596527756/
33
Collection Querying and Traversing
Iterative and Functional
Iterative Approach
Collection Querying and Traversing
 Native traversing can be done only on collections implementing
the Iterable<T> interface
 Set, Vector, List, Queue and AbstractCollection
List<String> names = new ArrayList<>();
for (String name : names) {
System.out.println(name);
}
36
Collection Querying and Traversing (1)
 Traversing cannot be done upon a Map<K,V> instance
 The <K> type in a Map instance is always unique (a map cannot
have duplicated keys)
 This allows to traverse the keys through a collection that does not
allow duplicates (Set)
 Method keySet()
from the Map<K,V> interface returns a Set
37
Collection Querying and Traversing (2)
 The <V> type in a Map instance allows duplicates.
 This allows to traverse the keys through an abstract collection
(Collection)
 Method values()
from the Map<K,V> interface returns an
abstract collection
38
Collection Querying and Traversing (3)
 To traverse the Key and Value pair, Java exposes a special
interface called Entry<K,V> similar to C#’s
KeyValuePair<TKey, TValue>
39
Collection Querying and Traversing (4)
 The pair K,V is always unique, because of the uniqueness of the
keyset.
 Thus the collection that holds Key-Value pair does not allow
duplicates (Set)
 To retrieve a collection of Key-Value pairs, the Map interface
exposes a method entrySet() which holds a Set of Entry
instances
40
Collection Querying and Traversing (5)
41
Collection Querying and Traversing (6)
 To query a collection one needs to iterate over it and find the
desired result.
List<String> names = new ArrayList<>();
names.add("gosho");
names.add("pesho");
String desiredName = null;
for (String name : names) {
if (name.equals("pesho") {
desiredName = name;
break;
}
}
42
Functional Approach
Collection Querying and Traversing (7)
 Querying a collection is also possible in a functional way
 Methods are chained returning a new query instance
 A terminal method is executed at the end
 This is all possible via the Stream API available from Java 8
44
Collection Querying and Traversing (8)
 Intermediate methods
 distinct()
– removes non-unique elements
 filter(Predicate<T>)
– filters elements (Where in LINQ)
Stream>) – transforms one Stream
to another Stream. May contain different type of elements
 flatMap(Function<T,
 limit(long)
– limits the elements in the new Stream
R>) – flatMap() without different types.
Same as Select in LINQ
 map(Function<T,
 sorted(Comparator?)
– sorts the elements in the Stream
45
Collection Querying and Traversing (9)
 Terminal methods
– checks whether all elements in
the Stream meets the predicate criteria (boolean)
 allMatch(Predicate<T>)
– checks whether at least one
element in the Stream meets the predicate criteria (boolean)
 anyMatch(<Predicate<T>)
A, R>) – converts a Stream to a
materialized collection (List, Map, Set…)
 collect(Collector<T,
– returns an element from the Stream. Returns
Optional<T> (same as Nullable<T> in C#)
 findAny()
46
Collection Querying and Traversing (9.1)
 Terminal methods (1)
 findFirst()
– returns the first element from the Stream
– executes the consumer
implementation upon each element. Void one.
 forEach(Consumer<T>)
– same as above but the
elements are ordered. Not thread-safe
 forEachOrdered(Consumer<T>)
– returns the maximum element by a
given criteria wrapped in Optional<T>
 max(Comparator<T>)
47
Collection Querying and Traversing (10)
List<String> names = new ArrayList<>();
names.stream()
.filter(n -> n.length() > 8)
.forEach(System.out::println);
Optional<String> first =
names.stream()
.findFirst();
System.out.println(first.get());
48
Collection Querying and Traversing (11)
LinkedHashMap<String, LinkedHashMap<String, Integer>> venues
= new LinkedHashMap<>();
venues.entrySet().stream().forEach(entry -> {
entry.getValue().entrySet().stream().sorted((innerEntry1, innerEntry2) -> {
return Integer.compare(innerEntry1.getValue(), innerEntry2.getValue());
}).forEach(innerEntry -> {
System.out.println(innerEntry.getKey());
System.out.println("-----------");
System.out.println(innerEntry.getValue());
});
});
49
Future References
 Monads with Java 8 Stream (Bulgarian)
http://www.cphpvb.net/java/9650-monads-with-java-8-stream/
50
Recursion
Recursion
Recursion
 In order to understand recursion one first has to understand
recursion
 Recursion is the process of repeating items in self-similar way
 Method calling itself until bottom is reached
 Recursion uses the system stack
52
Recursion (1)
 Recursion is highly used in traversal algorithms
53
Recursion (2)
 Traversing file system
 Each object of type File
is a file unless List<File> is
populated

Then it’s folder

This folder can have child folders with files too
54
Recursion (3)
public static void main(String[] args) {
File diskC = new File();
diskC.name = "Hard Drive (C)";
File autoexec = new File();
autoexec.name = "autoexec.bat"; // just a file
diskC.files.add(autoexec); // autoexec.bat is now child of disk C
File errorLog = new File();
errorLog.name = "errors.log"; // just a file
diskC.files.add(errorLog); // error.log is now child of disk C
}
55
Recursion (4)
 It’s easy to retrieve Disk C’s children
for (File f : diskC.files) {
System.out.println(f.name);
}
 But what if one of the files is a folder?
File windows = new File();
windows.name = "Windows";
File system32 = new File();
system32.name = "System 32";
windows.files.add(system32); // windows is a folder now
diskC.files.add(windows); // windows folder is child of disk C
56
Recursion (5)
 The foreach has to be called upon each child
57
Recursion (6)
 Starting from Disk C until reaching the last file
 Output:
58
Summary
 Arrays, Strings and Collections:
1.
Arrays: int[], String[], etc.
2.
Strings: String str = "Hello";
3.
Lists: ArrayList<E>
4.
Sets: HashSet<E>, TreeSet<E>
5.
Maps: HashMap<K, V>, TreeMap<K, V>
59
Java Collections
?
https://softuni.bg/courses/java-basics/
License
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons AttributionNonCommercial-ShareAlike 4.0 International" license
 Attribution: this work may contain portions from

"Fundamentals of Computer Programming with Java" book by Svetlin Nakov & Co. under CC-BY-SA license

"C# Basics" course by Software University under CC-BY-NC-SA license
61
Free Trainings @ Software University
 Software University Foundation – softuni.org
 Software University – High-Quality Education,
Profession and Job for Software Developers

softuni.bg
 Software University @ Facebook

facebook.com/SoftwareUniversity
 Software University @ YouTube

youtube.com/SoftwareUniversity
 Software University Forums – forum.softuni.bg
Download