SlideShare une entreprise Scribd logo
1  sur  35
Java Collections Basics
Arrays, Lists, Strings, Sets, Maps
Svetlin Nakov
Technical Trainer
www.nakov.com
Software University
http://softuni.bg
2
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>
Table of Contents
3
 The "Java Basics" 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
Warning: Not for Absolute Beginners
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)
5
0 1 2 3 4
Array of 5 elements
Element index
… … … … …
Element
of an array
6
 Allocating an array of 10 integers:
 Assigning values to the array elements:
 Accessing array elements by index:
Working with Arrays in Java
int[] numbers = new int[10];
for (int i=0; i<numbers.length; i++)
numbers[i] = i+1;
numbers[3] = 20;
numbers[5] = numbers[2] + numbers[7];
7
 You may define an array of any type, e.g. String:
Arrays of Strings
String[] names = { "Peter", "Maria", "Katya", "Todor" };
for (int i = 0; i<names.length; i++) {
System.out.printf("names[%d] = %sn", 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]);
}
Arrays
Live Demo
Lists
Using ArrayList<E>
11
 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
Lists in Java
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
System.out.println(numbers.get(0)); // 5
12
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);
13
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]
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!";
H e l l o , S o f t U n i !s
16
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
17
 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
Working with Strings
18
Strings – Examples
String str = "SoftUni";
System.out.println(str);
for (int i = 0; i < str.length(); i++) {
System.out.printf("str[%d] = %sn", 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
19
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(" nn Software University ".trim());
20
 The == operator does not work correctly for strings!
 Use String.equals(String) and String.compareTo(String)
Comparing Strings in Java
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
21
 Regular expressions match text by pattern, e.g.
 [0-9]+ matches a non-empty sequence of digits
 [a-zA-Z]* matches a sequence of letters (including empty)
 [A-Z][a-z]+ [A-Z][a-z]+ matches a name (first name +
space + last name)
 s+ matches any whitespace; S+ matches non-whitespace
 d+ matches digits; D+ matches non-digits
 w+ matches letters (Unicode); W+ matches non-letters
 +d{1,3}([ -]*[0-9]+)+ matches international phone
Regular Expressions
22
Validation by Regular Expression – Example
import java.util.regex.*;
…
String regex = "+d{1,3}([ -]*[0-9]+)+";
System.out.println("+359 2 981-981".matches(regex)); // true
System.out.println("invalid number".matches(regex)); // false
System.out.println("+359 123-".matches(regex)); // false
System.out.println("+359 (2) 981 981".matches(regex)); // false
System.out.println("+44 280 11 11".matches(regex)); // true
System.out.println("++44 280 11 11".matches(regex)); // false
System.out.println("(+49) 325 908 44".matches(regex)); // false
System.out.println("+49 325 908-40-40".matches(regex)); // true
23
Find Matches by Pattern – Example
import java.util.regex.*;
…
String text =
"Hello, my number in Sofia is +359 894 11 22 33, " +
"but in Munich my number is +49 89 975-99222.";
Pattern phonePattern = Pattern.compile(
"+d{1,3}([ -]*([0-9]+))+");
Matcher matcher = phonePattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
// +359 894 11 22 33
// +49 89 975-99222
Strings
Live Demos
Sets
HashSet<E> and TreeSet<E>
26
 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
Sets in Java
27
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]
Maps
29
 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
Maps in Java
30
 Counting words occurrences in a list:
HashMap<K, V> – Examples
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
 Students and their grades
TreeMap<K, V> – Examples
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
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>
Summary
?
https://softuni.bg/courses/java-basics/
Java Collections Basics
34
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-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
License
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

Contenu connexe

Tendances

15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories Intro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variablesIntro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and SetIntro C# Book
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm ComplexityIntro C# Book
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: ArraysSvetlin Nakov
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handlingIntro C# Book
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsSvetlin Nakov
 
Ch02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsCh02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsJames Brotsos
 
Java Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingJava Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingSvetlin Nakov
 
04. Console Input Output
04. Console Input Output 04. Console Input Output
04. Console Input Output Intro C# Book
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple ProgramsUpender Upr
 

Tendances (20)

09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
10. Recursion
10. Recursion10. Recursion
10. Recursion
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
 
06.Loops
06.Loops06.Loops
06.Loops
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
 
09. Methods
09. Methods09. Methods
09. Methods
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
Ch02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsCh02 primitive-data-definite-loops
Ch02 primitive-data-definite-loops
 
Chapter 2 Java Methods
Chapter 2 Java MethodsChapter 2 Java Methods
Chapter 2 Java Methods
 
Parameters
ParametersParameters
Parameters
 
Java Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingJava Foundations: Strings and Text Processing
Java Foundations: Strings and Text Processing
 
04. Console Input Output
04. Console Input Output 04. Console Input Output
04. Console Input Output
 
Java Basics - Part1
Java Basics - Part1Java Basics - Part1
Java Basics - Part1
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 

Similaire à 07. Java Array, Set and Maps

L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)teach4uin
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................suchitrapoojari984
 
Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsClass notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsKuntal Bhowmick
 
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)KonfHubTechConferenc
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptxSajalFayyaz
 
Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsClass notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsKuntal Bhowmick
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009David Pollak
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and InformationSoftNutx
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 

Similaire à 07. Java Array, Set and Maps (20)

Lecture 6
Lecture 6Lecture 6
Lecture 6
 
Meet scala
Meet scalaMeet scala
Meet scala
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsClass notes(week 4) on arrays and strings
Class notes(week 4) on arrays and strings
 
Data structures
Data structures Data structures
Data structures
 
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptx
 
L5 array
L5 arrayL5 array
L5 array
 
Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsClass notes(week 4) on arrays and strings
Class notes(week 4) on arrays and strings
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Chap1 array
Chap1 arrayChap1 array
Chap1 array
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and Information
 
Scala
ScalaScala
Scala
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 

Plus de Intro C# Book

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversalIntro C# Book
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming CodeIntro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism Intro C# Book
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulationIntro C# Book
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritanceIntro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arraysIntro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classesIntro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with javaIntro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem SolvingIntro C# Book
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming CodeIntro C# Book
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like StructuresIntro C# Book
 

Plus de Intro C# Book (15)

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
 
14 Defining Classes
14 Defining Classes14 Defining Classes
14 Defining Classes
 

Dernier

Al Barsha Night Partner +0567686026 Call Girls Dubai
Al Barsha Night Partner +0567686026 Call Girls  DubaiAl Barsha Night Partner +0567686026 Call Girls  Dubai
Al Barsha Night Partner +0567686026 Call Girls DubaiEscorts Call Girls
 
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...SUHANI PANDEY
 
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort ServiceBusty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort ServiceDelhi Call girls
 
Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...tanu pandey
 
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...SUHANI PANDEY
 
Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirtrahman018755
 
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...roncy bisnoi
 
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRLLucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRLimonikaupta
 
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdfMatthew Sinclair
 
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency""Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency"growthgrids
 
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...nilamkumrai
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdfMatthew Sinclair
 
APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC
 
VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...
VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...
VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...SUHANI PANDEY
 
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...SUHANI PANDEY
 

Dernier (20)

Al Barsha Night Partner +0567686026 Call Girls Dubai
Al Barsha Night Partner +0567686026 Call Girls  DubaiAl Barsha Night Partner +0567686026 Call Girls  Dubai
Al Barsha Night Partner +0567686026 Call Girls Dubai
 
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
 
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
 
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort ServiceBusty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
 
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
 
Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
 
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
 
Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirt
 
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
 
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRLLucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
 
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
 
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
 
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency""Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
 
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf
 
Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵
Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵
Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵
 
APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53
 
VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...
VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...
VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...
 
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...
 

07. Java Array, Set and Maps

  • 1. Java Collections Basics Arrays, Lists, Strings, Sets, Maps Svetlin Nakov Technical Trainer www.nakov.com Software University http://softuni.bg
  • 2. 2 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> Table of Contents
  • 3. 3  The "Java Basics" 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 Warning: Not for Absolute Beginners
  • 5. 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) 5 0 1 2 3 4 Array of 5 elements Element index … … … … … Element of an array
  • 6. 6  Allocating an array of 10 integers:  Assigning values to the array elements:  Accessing array elements by index: Working with Arrays in Java int[] numbers = new int[10]; for (int i=0; i<numbers.length; i++) numbers[i] = i+1; numbers[3] = 20; numbers[5] = numbers[2] + numbers[7];
  • 7. 7  You may define an array of any type, e.g. String: Arrays of Strings String[] names = { "Peter", "Maria", "Katya", "Todor" }; for (int i = 0; i<names.length; i++) { System.out.printf("names[%d] = %sn", 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. 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]); }
  • 11. 11  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 Lists in Java ArrayList<Integer> numbers = new ArrayList<Integer>(); numbers.add(5); System.out.println(numbers.get(0)); // 5
  • 12. 12 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);
  • 13. 13 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]
  • 16. 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!"; H e l l o , S o f t U n i !s 16 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
  • 17. 17  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 Working with Strings
  • 18. 18 Strings – Examples String str = "SoftUni"; System.out.println(str); for (int i = 0; i < str.length(); i++) { System.out.printf("str[%d] = %sn", 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
  • 19. 19 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(" nn Software University ".trim());
  • 20. 20  The == operator does not work correctly for strings!  Use String.equals(String) and String.compareTo(String) Comparing Strings in Java 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
  • 21. 21  Regular expressions match text by pattern, e.g.  [0-9]+ matches a non-empty sequence of digits  [a-zA-Z]* matches a sequence of letters (including empty)  [A-Z][a-z]+ [A-Z][a-z]+ matches a name (first name + space + last name)  s+ matches any whitespace; S+ matches non-whitespace  d+ matches digits; D+ matches non-digits  w+ matches letters (Unicode); W+ matches non-letters  +d{1,3}([ -]*[0-9]+)+ matches international phone Regular Expressions
  • 22. 22 Validation by Regular Expression – Example import java.util.regex.*; … String regex = "+d{1,3}([ -]*[0-9]+)+"; System.out.println("+359 2 981-981".matches(regex)); // true System.out.println("invalid number".matches(regex)); // false System.out.println("+359 123-".matches(regex)); // false System.out.println("+359 (2) 981 981".matches(regex)); // false System.out.println("+44 280 11 11".matches(regex)); // true System.out.println("++44 280 11 11".matches(regex)); // false System.out.println("(+49) 325 908 44".matches(regex)); // false System.out.println("+49 325 908-40-40".matches(regex)); // true
  • 23. 23 Find Matches by Pattern – Example import java.util.regex.*; … String text = "Hello, my number in Sofia is +359 894 11 22 33, " + "but in Munich my number is +49 89 975-99222."; Pattern phonePattern = Pattern.compile( "+d{1,3}([ -]*([0-9]+))+"); Matcher matcher = phonePattern.matcher(text); while (matcher.find()) { System.out.println(matcher.group()); } // +359 894 11 22 33 // +49 89 975-99222
  • 26. 26  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 Sets in Java
  • 27. 27 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]
  • 28. Maps
  • 29. 29  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 Maps in Java
  • 30. 30  Counting words occurrences in a list: HashMap<K, V> – Examples 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. 31  Students and their grades TreeMap<K, V> – Examples 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. 32 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> Summary
  • 34. 34  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-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 License
  • 35. 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