Java Collections Arrays, Lists, Strings, Sets, Maps SoftUni Team Technical Trainers Software University

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

JavaScript Basics Course Introduction SoftUni Team Technical Trainers Software University
Software Quality Assurance QA Engineering, Testing, Bug Tracking, Test Automation Software University Technical Trainers SoftUni Team.
FEN 2012UCN Technology - Computer Science 1 Data Structures and Collections Principles revisited.NET: –Two libraries: System.Collections System.Collections.Generics.
C# Advanced Topics Methods, Classes and Objects SoftUni Team Technical Trainers Software University
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
PHP Basics Course Introduction SoftUni Team Technical Trainers Software University
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Loops, Methods, Classes Loops, Methods, Using API Classes, Exceptions SoftUni Team Technical Trainer Software University
Programming Basics Course Introduction SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
NoSQL Databases NoSQL Concepts SoftUni Team Technical Trainers Software University
Conditional Statements Implementing Control-Flow Logic in C# SoftUni Team Technical Trainers Software University
Course Program, Evaluation, Exams
Redis Key-Value Database: Practical Introduction
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
Methods, Arrays, Lists, Dictionaries, Strings, Classes and Objects
Svetlin Nakov Technical Trainer Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers Software University.
Loops, Methods, Classes Using Loops, Defining and Using Methods, Using API Classes, Exceptions, Defining Classes Bogomil Dimitrov Technical Trainer Software.
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Static Members and Namespaces Static Members, Indexers, Operators, Namespaces SoftUni Team Technical Trainers Software University
JavaScript Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Java Collections Basics Arrays, Lists, Strings, Sets, Maps Svetlin Nakov Technical Trainer Software University
Graphs and Graph Algorithms Fundamentals, Terminology, Traversal, Algorithms SoftUni Team Technical Trainers Software University
Arrays, Lists, Stacks, Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Using SQL Connecting, Retrieving Data, Executing SQL Commands, … Svetlin Nakov Technical Trainer Software University
C# Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
Exam Preparation Algorithms Course: Sample Exam SoftUni Team Technical Trainers Software University
Associative Arrays and Objects Associative Arrays, Objects Svetlin Nakov Technical Trainer Software University
Java Collections Basics Arrays, Lists, Strings, Sets, Maps Bogomil Dimitrov Technical Trainer Software University
Maps Nick Mouriski.
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
Advanced C# Course Introduction SoftUni Team Technical Trainers Software University
Prototype Chain and Inheritance Prototype chain, Inheritance, Accessing Base Members Software University Technical Trainers SoftUni Team.
C# Advanced Topics Methods, Arrays, Lists, Dictionaries, Strings, Classes and Objects SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Operators and Expressions
Data Structures Curriculum, Trainers, Evaluation, Exams SoftUni Team Technical Trainers Software University
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Programming for Beginners Course Introduction SoftUni Team Technical Trainers Software University
Processing Sequences of Elements
Sets, Dictionaries SoftUni Team Technical Trainers Software University
Lists and Matrices Lists: Variable-Size Arrays Matrices: Arrays of Arrays (Tables) SoftUni Team Technical Trainers Software University
Advanced Tree Structures Binary Trees, AVL Tree, Red-Black Tree, B-Trees, Heaps SoftUni Team Technical Trainers Software University
Loops, Methods, Classes Using Loops, Defining and Using Methods, Using API Classes, Exceptions, Defining Classes Svetlin Nakov Technical Trainer
PHP Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Programming Fundamentals Course Introduction SoftUni Team Technical Trainers Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Static Members Static Variables & Methods SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
Arrays, Lists, Stacks, Queues
Methods, Arrays, Lists, Dictionaries, Strings, Classes and Objects
Processing Variable-Length Sequences of Elements
Functional Programming and Stream API
Functional Programming
Text Processing and Regex API
Multidimensional Arrays
Presentation transcript:

Java Collections Arrays, Lists, Strings, Sets, Maps SoftUni Team Technical Trainers Software University

2 1.Arrays  int[], String[], etc. 2.Lists  ArrayList 3.Strings  String str = "Hello"; 4.Sets  HashSet, TreeSet 5.Maps  HashMap, TreeMap Table of Contents

3  The "Java Fundamentals" course is NOT for absolute beginners  Take the "C# Basics" course at SoftUni first:  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 ) Array of 5 elements Element index …………… Element of an array

6  Reference data type  Variable “classmates” holds addresses in the heap as values.  Each address points to a separate value in the heap memory. How arrays are stored in the memory

7  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[i] = i+1; numbers[3] = 20; numbers[5] = numbers[2] + numbers[7];

8  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] = %s\n", i, names[i]); System.out.printf("names[%d] = %s\n", i, names[i]);} for (String name : names) { System.out.println(name); System.out.println(name);} names[4] = "Nakov"; // ArrayIndexOutOfBoundsException names.length = 5; // array.length is read-only field

9 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(); lines[i] = scanner.nextLine();}Arrays.sort(lines); for (int i = 0; i < lines.length; i++) { System.out.println(lines[i]); System.out.println(lines[i]);}

Arrays Live Demo

Lists Using ArrayList

12  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 class  Where E is the type of the list, e.g. String or Integer Lists in Java ArrayList numbers = new ArrayList (); numbers.add(5); System.out.println(numbers.get(0)); // 5

13  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 Arrays vs ArrayLists How array lists are stored in the memory

14 ArrayList – Example ArrayList names = new ArrayList () {{ 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 // 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);

15 ArrayList – Example // This will not compile! ArrayList intArr = new ArrayList (); ArrayList nums = new ArrayList<>( Arrays.asList(5, -3, 10, 25)); 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 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!"; Hello, SoftUni!s

19  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

20 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.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

21 Strings – Examples (2) String firstName = "Steve"; String lastName = "Jobs"; int age = 56; System.out.println(firstName + " " + lastName + " (age: " + age + ")"); // Steve Jobs (age: 56) " (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(lang);} System.out.println("Langs = " + String.join(", ", langs)); System.out.println(" \n\n Software University ".trim());

22  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

Strings Live Demos

Sets HashSet and TreeSet

25  Sets in Java keep unique elements  Like lists but duplicated elements are stored only once  HashSet  Keeps a set of elements in a hash-tables  The elements are randomly ordered (by their hash code)  TreeSet  Keeps a set of elements in a red-black ordered search tree  The elements are ordered incrementally Sets in Java

26  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 HashSet  TreeSet TreeSet How hash sets are stored in the memory

27 HashSet and TreeSet – Examples Set set = new TreeSet (); 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 pairs  HashMap  Keeps a map of elements in a hash-table  The elements are randomly ordered (by their hash code)  TreeMap  Keeps a set of elements in a red-black ordered search tree  The elements are ordered incrementally by their key Maps in Java

30  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. How hash maps are stored in the memory

31  Counting words occurrences in a list: HashMap – Examples String[] words = { "yes", "hi", "hello", "hi", "welcome", "yes", "yes", "welcome", "hi", "yes", "hello", "yes" }; "yes", "yes", "welcome", "hi", "yes", "hello", "yes" }; Map wordsCount = new HashMap (); for (String word : words) { Integer count = wordsCount.get(word); Integer count = wordsCount.get(word); if (count == null) { if (count == null) { count = 0; count = 0; } wordsCount.put(word, count+1); wordsCount.put(word, count+1);} System.out.println(wordsCount); // {hi=3, yes=5, hello=2, welcome=2}

32  Students and their grades TreeMap – Examples HashMap > 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)); System.out.println("" + key + " -> " + grades.get(key));}

33  Java Oracle documentation  The book “Java Generics and Collections” Future References

Collection Querying and Traversing Iterative and Functional

Iterative Approach

36  Native traversing can be done only on collections implementing the Iterable interface  Set, Vector, List, Queue and AbstractCollection Collection Querying and Traversing <> names = ArrayList<>() (name : names) {..(name) } List names = new ArrayList<>(); for (String name : names) { System.out.println(name); }

37  Traversing cannot be done upon a Map instance  The 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 interface returns a Set Collection Querying and Traversing (1)

38  The type in a Map instance allows duplicates.  This allows to traverse the keys through an abstract collection ( Collection )  Method values() from the Map interface returns an abstract collection Collection Querying and Traversing (2)

39  To traverse the Key and Value pair, Java exposes a special interface called Entry similar to C#’s KeyValuePair Collection Querying and Traversing (3)

40  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 Collection Querying and Traversing (4)

41 Collection Querying and Traversing (5)

42  To query a collection one needs to iterate over it and find the desired result. Collection Querying and Traversing (6) <> names = ArrayList<>() names.() names.() desiredName = (name : names) { (name.() { desiredName = name } } List names = new ArrayList<>(); names.add("gosho"); names.add("pesho"); String desiredName = null; for (String name : names) { if (name.equals("pesho") { desiredName = name; break; } }

Functional Approach

44  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 Collection Querying and Traversing (7)

45  Intermediate methods  distinct() – removes non-unique elements  filter(Predicate ) – filters elements (Where in LINQ)  flatMap(Function ) – transforms one Stream to another Stream. May contain different type of elements  limit(long) – limits the elements in the new Stream  map(Function ) – flatMap() without different types. Same as Select in LINQ  sorted(Comparator?) – sorts the elements in the Stream Collection Querying and Traversing (8)

46  Terminal methods  allMatch(Predicate ) – checks whether all elements in the Stream meets the predicate criteria (boolean)  anyMatch( ) – checks whether at least one element in the Stream meets the predicate criteria (boolean)  collect(Collector ) – converts a Stream to a materialized collection (List, Map, Set…)  findAny() – returns an element from the Stream. Returns Optional (same as Nullable in C#) Collection Querying and Traversing (9)

47  Terminal methods (1)  findFirst() – returns the first element from the Stream  forEach(Consumer ) – executes the consumer implementation upon each element. Void one.  forEachOrdered(Consumer ) – same as above but the elements are ordered. Not thread-safe  max(Comparator ) – returns the maximum element by a given criteria wrapped in Optional Collection Querying and Traversing (9.1)

48 Collection Querying and Traversing (10) <> names = ArrayList<>() names.().(n -> n.() > ).(.::) <> first = names.().()..(first.()) List names = new ArrayList<>(); names.stream().filter(n -> n.length() > 8).forEach(System.out::println); Optional first = names.stream().findFirst(); System.out.println(first.get());

49 Collection Querying and Traversing (11) > venues = <>() venues.().().(entry -> { entry.().().().((innerEntry1innerEntry2) -> {.(innerEntry1.()innerEntry2.()) }).(innerEntry -> {..(innerEntry.())..()..(innerEntry.()) }) }) LinkedHashMap > 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()); }); });

50  Monads with Java 8 Stream (Bulgarian) Future References

Recursion

52  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 Recursion

53  Recursion is highly used in traversal algorithms Recursion (1)

54  Traversing file system  Each object of type File is a file unless List is populated  Then it’s folder  This folder can have child folders with files too Recursion (2)

55 Recursion (3) ([] args) { diskC = () diskC.= autoexec = () autoexec.= diskC..(autoexec) errorLog = () errorLog.= diskC..(errorLog) } 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 }

56  It’s easy to retrieve Disk C’s children  But what if one of the files is a folder? Recursion (4) (f : diskC.) {..(f.) } for (File f : diskC.files) { System.out.println(f.name); } windows = () windows.= system32 = () system32.= windows..(system32) diskC..(windows) 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

57  The foreach has to be called upon each child Recursion (5)

58  Starting from Disk C until reaching the last file  Output: Recursion (6)

59  Arrays, Strings and Collections: 1. Arrays: int[], String[], etc. 2. Strings: String str = "Hello"; 3. Lists: ArrayList 4. Sets: HashSet, TreeSet 5. Maps: HashMap, TreeMap Summary

? ? ? ? ? ? ? ? ? Java Collections

61  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with Java" book by Svetlin Nakov & Co. under CC-BY-SA licenseFundamentals of Computer Programming with JavaCC-BY-SA  "C# Basics" course by Software University under CC-BY-NC-SA licenseC# BasicsCC-BY-NC-SA License

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg