SlideShare a Scribd company logo
Java Foundations
Lists, List<T>,
ArrayList<T>
Your Course
Instructors
Svetlin Nakov
George Georgiev
The Judge System
Sending your Solutions
for Automated Evaluation
Testing Your Code in the Judge System
 Test your code online in the SoftUni Judge system:
https://judge.softuni.org/Contests/3294
Lists in Java
Processing Variable Length
Sequences of Elements
Table of Contents
1. Lists: Overview
2. List Manipulating: Add, Delete, Insert, Clear
3. Reading Lists from the Console. Printing Lists
4. Sorting Lists and Arrays
7
Lists in Java
8
List<E> – Overview
 List<E> holds a list of elements of any type
9
List<String> names = new ArrayList<>();
// Create a list of strings
names.add("Peter");
names.add("Maria");
names.add("George");
names.remove("Maria");
for (String name : names)
System.out.println(name);
// Peter, George
List<E> – Overview (2)
10
List<Integer> nums = new ArrayList<>(
Arrays.asList(10, 20, 30, 40, 50, 60));
nums.remove(2);
nums.remove(Integer.valueOf(40));
nums.add(100);
nums.add(0, -100);
for (int i = 0; i < nums.size(); i++)
System.out.print(nums.get(i) + " ");
-100 10 20 50 60 100
Inserts an element to index
Items count
Remove by index
Remove by value (slow)
 List<E> holds a list of elements (like array, but extendable)
 Provides operations to add / insert / remove / find elements:
 size() – number of elements in the List<E>
 add(element) – adds an element to the List<E>
 add(index, element) – inserts an element to given position
 remove(element) – removes an element (returns true / false)
 remove(index) – removes element at index
 contains(element) – determines whether an element is in the list
 set(index, item) – replaces the element at the given index
List<E> – Data Structure
11
add – Appends an Element
12
10
5
2
0
Count: 1
2
3
List<Integer>
10
5
2
10
remove – Deletes an Element
13
2
5
Count:
List<Integer>
10
2
3
10
add (index, el) – Inserts an Element at Position
14
3
2
2
5
Count:
List<Integer>
-5
-5
Reading Lists from the Console
Using for Loop or String.split()
15
 First, read from the console the array length:
 Next, create a list of given size n and read its elements:
Reading Lists From the Console
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int number = Integer.parseInt(sc.nextLine());
list.add(number);
}
 Lists can be read from a single line of space separated values:
Reading List Values from a Single Line
17
2 8 30 25 40 72 -2 44 56
String values = sc.nextLine();
List<String> items = Arrays.stream(values.split(" "))
.collect(Collectors.toList());
List<Integer> nums = new ArrayList<>();
for (int i = 0; i < items.size(); i++)
nums.add(Integer.parseInt(items.get(i)));
Convert a collection
into List
List<Integer> items = Arrays.stream(values.split(" "))
.map(Integer::parseInt).collect(Collectors.toList());
 Printing a list using a for-loop:
 Printing a list using a String.join():
Printing Lists on the Console
18
List<String> list = new ArrayList<>(Arrays.asList(
"one", "two", "three", "four", "five", "six"));
for (int index = 0; index < list.size(); index++)
System.out.printf
("arr[%d] = %s%n", index, list.get(index));
List<String> list = new ArrayList<>(Arrays.asList(
"one", "two", "three", "four", "five", "six"));
System.out.println(String.join("; ", list));
Gets an element
at given index
 Write a program to sum all adjacent equal numbers in a list of
decimal numbers, starting from left to right
 Examples:
Problem: Sum Adjacent Equal Numbers
19
3 3 6 1 12 1
8 2 2 4 8 16 16 8 16
5 4 2 1 1 4 5 8 4
Scanner sc = new Scanner(System.in);
List<Double> numbers = Arrays.stream(sc.nextLine().split(" "))
.map(Double::parseDouble).collect(Collectors.toList());
for (int i = 0; i < numbers.size() - 1; i++)
if (numbers.get(i).equals(numbers.get(i + 1))) {
numbers.set(i, numbers.get(i) + numbers.get(i + 1));
numbers.remove(i + 1);
i = -1;
}
// Continues on the next slide
Solution: Sum Adjacent Equal Numbers (1)
0
Solution: Sum Adjacent Equal Numbers (2)
21
static String joinElementsByDelimiter
(List<Double> items, String delimiter) {
String output = "";
for (Double item : items)
output += (new DecimalFormat("0.#").format(item) + delimiter);
return output;
}
String output = joinElementsByDelimiter(numbers, " ");
System.out.println(output);
 Write a program that sums all numbers in a list in the
following order:
 first + last, first + 1 + last - 1, first + 2 + last - 2, … first + n, last – n
 Examples:
Problem: Gauss' Trick
22
1 2 3 4 5 6 6 3
1 2 3 4 5 5
Solution: Gauss' Trick
3
Scanner sc = new Scanner(System.in);
List<Integer> numbers = Arrays.stream(sc.nextLine().split(" "))
.map(Integer::parseInt).collect(Collectors.toList());
int size = numbers.size();
for (int i = 0; i < size / 2; i++) {
numbers.set(i, numbers.get(i) + numbers.get(numbers.size() - 1));
numbers.remove(numbers.size() - 1);
}
System.out.println(numbers.toString().replaceAll("[[],]", ""));
 You receive two lists with numbers. Print a result list which
contains the numbers from both lists
 If the length of the two lists is not equal, just add the
remaining elements at the end of the list
 list1[0], list2[0], list1[1], list2[1], …
Problem: Merging Lists
24
1 2 3 4 5
6 7 8
1 6 2 7 3 8 4 5
// TODO: Read the input
List<Integer> resultNums = new ArrayList<>();
for (int i = 0; i < Math.min(nums1.size(), nums2.size()); i++) {
// TODO: Add numbers in resultNums
}
if (nums1.size() > nums2.size())
resNums.addAll(getRemainingElements(nums1, nums2));
else if (nums2.size() > nums1.size())
resNums.addAll(getRemainingElements(nums2, nums1));
System.out.println(resNums.toString().replaceAll("[[],]", ""));
Solution: Merging Lists (1)
25
public static List<Integer> getRemainingElements
(List<Integer> longerList, List<Integer> shorterList) {
List<Integer> nums = new ArrayList<>();
for (int i = shorterList.size(); i < longerList.size(); i++)
nums.add(longerList.get(i));
return nums;
}
Solution: Merging Lists (2)
26
Live Exercises
Reading and Manipulating Lists
Sorting Lists and Arrays
28
 Sorting a list == reorder its elements incrementally: Sort()
 List items should be comparable, e.g. numbers, strings, dates, …
Sorting Lists
List<String> names = new ArrayList<>(Arrays.asList(
"Peter", "Michael", "George", "Victor", "John"));
Collections.sort(names);
System.out.println(String.join(", ", names));
// George, John, Michael, Peter, Victor
Collections.sort(names);
Collections.reverse(names);
System.out.println(String.join(", ", names));
// Victor, Peter, Michael, John, George
Sort in natural
(ascending) order
Reverse the sorted result
 Read a number n and n lines of products. Print a numbered list
of all the products ordered by name
 Examples:
Problem: List of Products
30
4
Potatoes
Tomatoes
Onions
Apples
1.Apples
2.Onions
3.Potatoes
4.Tomatoes
A
Z
int n = Integer.parseInt(sc.nextLine());
List<String> products = new ArrayList<>();
for (int i = 0; i < n; i++) {
String currentProduct = sc.nextLine();
products.add(currentProduct);
}
Collections.sort(products);
for (int i = 0; i < products.size(); i++)
System.out.printf("%d.%s%n", i + 1, products.get(i));
Solution: List of Products
 Read a list of integers, remove all negative numbers from it
 Print the remaining elements in reversed order
 In case of no elements left in the list, print "empty"
Problem: Remove Negatives and Reverse
32
10 -5 7 9 -33 50 50 9 7 10
7 -2 -10 1 1 7
-1 -2 -3 empty
List<Integer> nums = Arrays.stream(sc.nextLine().split(" "))
.map(Integer::parseInt).collect(Collectors.toList());
for (int i = 0; i < nums.size(); i++)
if (nums.get(i) < 0)
nums.remove(i--);
Collections.reverse(nums);
if (nums.size() == 0)
System.out.println("empty");
else
System.out.println(nums.toString().replaceAll("[[],]", ""));
Solution: Remove Negatives and Reverse
Live Exercises
Sorting Lists
 …
 …
 …
Summary
35
 Lists hold a sequence of elements
(variable-length)
 Can add / remove / insert elements
at runtime
 Creating (allocating) a list:
new ArrayList<E>()
 Accessing list elements by index
 Printing list elements: String.join(…)
 …
 …
 …
Next Steps
 Join the SoftUni "Learn To Code" Community
 Access the Free Coding Lessons
 Get Help from the Mentors
 Meet the Other Learners
https://softuni.org

More Related Content

What's hot (20)

Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
Svetlin Nakov
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
Intro C# Book
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
Svetlin Nakov
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
Sunil OS
 
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
Intro C# Book
 
JDBC
JDBCJDBC
JDBC
Sunil OS
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
Intro C# Book
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
Sunil OS
 
[OKKYCON] 정진욱 - 테스트하기 쉬운 코드로 개발하기
[OKKYCON] 정진욱 - 테스트하기 쉬운 코드로 개발하기[OKKYCON] 정진욱 - 테스트하기 쉬운 코드로 개발하기
[OKKYCON] 정진욱 - 테스트하기 쉬운 코드로 개발하기
OKKY
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
Sunil OS
 
Expressjs
ExpressjsExpressjs
Expressjs
Yauheni Nikanovich
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVM
Rafael Winterhalter
 
Java Coleções
Java ColeçõesJava Coleções
Java Coleções
Mario Jorge Pereira
 
Урок 20. Практична робота №7. Розміщення аудіо- та відеоматеріалів в Інтернеті
Урок 20. Практична робота №7. Розміщення аудіо- та відеоматеріалів в ІнтернетіУрок 20. Практична робота №7. Розміщення аудіо- та відеоматеріалів в Інтернеті
Урок 20. Практична робота №7. Розміщення аудіо- та відеоматеріалів в Інтернеті
Василь Тереховський
 
Java 8 Default Methods
Java 8 Default MethodsJava 8 Default Methods
Java 8 Default Methods
Haim Michael
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
Sunil OS
 
Unit testing framework
Unit testing frameworkUnit testing framework
Unit testing framework
Igor Vavrish
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
DJango
DJangoDJango
DJango
Sunil OS
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
Svetlin Nakov
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
Intro C# Book
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
Svetlin Nakov
 
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
Intro C# Book
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
Sunil OS
 
[OKKYCON] 정진욱 - 테스트하기 쉬운 코드로 개발하기
[OKKYCON] 정진욱 - 테스트하기 쉬운 코드로 개발하기[OKKYCON] 정진욱 - 테스트하기 쉬운 코드로 개발하기
[OKKYCON] 정진욱 - 테스트하기 쉬운 코드로 개발하기
OKKY
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
Sunil OS
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVM
Rafael Winterhalter
 
Урок 20. Практична робота №7. Розміщення аудіо- та відеоматеріалів в Інтернеті
Урок 20. Практична робота №7. Розміщення аудіо- та відеоматеріалів в ІнтернетіУрок 20. Практична робота №7. Розміщення аудіо- та відеоматеріалів в Інтернеті
Урок 20. Практична робота №7. Розміщення аудіо- та відеоматеріалів в Інтернеті
Василь Тереховський
 
Java 8 Default Methods
Java 8 Default MethodsJava 8 Default Methods
Java 8 Default Methods
Haim Michael
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
Sunil OS
 
Unit testing framework
Unit testing frameworkUnit testing framework
Unit testing framework
Igor Vavrish
 

Similar to Java Foundations: Lists, ArrayList<T> (20)

22.ppt
22.ppt22.ppt
22.ppt
BharaniDaran15
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
arshin9
 
A popular implementation of List is ArrayList- Look up how to instanti.pdf
A popular implementation of List is ArrayList- Look up how to instanti.pdfA popular implementation of List is ArrayList- Look up how to instanti.pdf
A popular implementation of List is ArrayList- Look up how to instanti.pdf
arsarees
 
CF5_Unit4.ppt.pdf java collection frameworks
CF5_Unit4.ppt.pdf java collection frameworksCF5_Unit4.ppt.pdf java collection frameworks
CF5_Unit4.ppt.pdf java collection frameworks
mpfbaa
 
Array list
Array listArray list
Array list
vishal choudhary
 
I am stuck on parts E and FExercise 1      NumberListTester.java.pdf
I am stuck on parts E and FExercise 1      NumberListTester.java.pdfI am stuck on parts E and FExercise 1      NumberListTester.java.pdf
I am stuck on parts E and FExercise 1      NumberListTester.java.pdf
RAJATCHUGH12
 
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfJAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
arpaqindia
 
lec6.ppt
lec6.pptlec6.ppt
lec6.ppt
cawarir
 
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answeredU-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
zainmkhan20
 
Write a java class LIST that outputsmainpublic class Ass.pdf
Write a java class LIST that outputsmainpublic class Ass.pdfWrite a java class LIST that outputsmainpublic class Ass.pdf
Write a java class LIST that outputsmainpublic class Ass.pdf
ebrahimbadushata00
 
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
davidwarner122
 
Arrays and Strings engineering education
Arrays and Strings engineering educationArrays and Strings engineering education
Arrays and Strings engineering education
csangani1
 
Engineering lecture ppt by venay magen
Engineering lecture ppt by venay magenEngineering lecture ppt by venay magen
Engineering lecture ppt by venay magen
venaymagen19
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
talha ijaz
 
arraylist in java a comparison of the array and arraylist
arraylist in java a comparison of the array and arraylistarraylist in java a comparison of the array and arraylist
arraylist in java a comparison of the array and arraylist
PriyadharshiniG41
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and Information
SoftNutx
 
Arrays in Java with example and types of array.pptx
Arrays in Java with example and types of array.pptxArrays in Java with example and types of array.pptx
Arrays in Java with example and types of array.pptx
ashwinibhosale27
 
Data Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptxData Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptx
RashidFaridChishti
 
Question 1 MiniList collection 20 marks In this question .pdf
Question 1 MiniList collection 20 marks In this question .pdfQuestion 1 MiniList collection 20 marks In this question .pdf
Question 1 MiniList collection 20 marks In this question .pdf
abhisheksharmasre
 
Aj unit2 notesjavadatastructures
Aj unit2 notesjavadatastructuresAj unit2 notesjavadatastructures
Aj unit2 notesjavadatastructures
Arthik Daniel
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
arshin9
 
A popular implementation of List is ArrayList- Look up how to instanti.pdf
A popular implementation of List is ArrayList- Look up how to instanti.pdfA popular implementation of List is ArrayList- Look up how to instanti.pdf
A popular implementation of List is ArrayList- Look up how to instanti.pdf
arsarees
 
CF5_Unit4.ppt.pdf java collection frameworks
CF5_Unit4.ppt.pdf java collection frameworksCF5_Unit4.ppt.pdf java collection frameworks
CF5_Unit4.ppt.pdf java collection frameworks
mpfbaa
 
I am stuck on parts E and FExercise 1      NumberListTester.java.pdf
I am stuck on parts E and FExercise 1      NumberListTester.java.pdfI am stuck on parts E and FExercise 1      NumberListTester.java.pdf
I am stuck on parts E and FExercise 1      NumberListTester.java.pdf
RAJATCHUGH12
 
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfJAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
arpaqindia
 
lec6.ppt
lec6.pptlec6.ppt
lec6.ppt
cawarir
 
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answeredU-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
zainmkhan20
 
Write a java class LIST that outputsmainpublic class Ass.pdf
Write a java class LIST that outputsmainpublic class Ass.pdfWrite a java class LIST that outputsmainpublic class Ass.pdf
Write a java class LIST that outputsmainpublic class Ass.pdf
ebrahimbadushata00
 
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
davidwarner122
 
Arrays and Strings engineering education
Arrays and Strings engineering educationArrays and Strings engineering education
Arrays and Strings engineering education
csangani1
 
Engineering lecture ppt by venay magen
Engineering lecture ppt by venay magenEngineering lecture ppt by venay magen
Engineering lecture ppt by venay magen
venaymagen19
 
arraylist in java a comparison of the array and arraylist
arraylist in java a comparison of the array and arraylistarraylist in java a comparison of the array and arraylist
arraylist in java a comparison of the array and arraylist
PriyadharshiniG41
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and Information
SoftNutx
 
Arrays in Java with example and types of array.pptx
Arrays in Java with example and types of array.pptxArrays in Java with example and types of array.pptx
Arrays in Java with example and types of array.pptx
ashwinibhosale27
 
Data Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptxData Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptx
RashidFaridChishti
 
Question 1 MiniList collection 20 marks In this question .pdf
Question 1 MiniList collection 20 marks In this question .pdfQuestion 1 MiniList collection 20 marks In this question .pdf
Question 1 MiniList collection 20 marks In this question .pdf
abhisheksharmasre
 
Aj unit2 notesjavadatastructures
Aj unit2 notesjavadatastructuresAj unit2 notesjavadatastructures
Aj unit2 notesjavadatastructures
Arthik Daniel
 
Ad

More from Svetlin Nakov (20)

AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
Svetlin Nakov
 
AI за ежедневието - Наков @ Techniverse (Nov 2024)
AI за ежедневието - Наков @ Techniverse (Nov 2024)AI за ежедневието - Наков @ Techniverse (Nov 2024)
AI за ежедневието - Наков @ Techniverse (Nov 2024)
Svetlin Nakov
 
AI инструменти за бизнеса - Наков - Nov 2024
AI инструменти за бизнеса - Наков - Nov 2024AI инструменти за бизнеса - Наков - Nov 2024
AI инструменти за бизнеса - Наков - Nov 2024
Svetlin Nakov
 
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
Svetlin Nakov
 
Software Engineers in the AI Era - Sept 2024
Software Engineers in the AI Era - Sept 2024Software Engineers in the AI Era - Sept 2024
Software Engineers in the AI Era - Sept 2024
Svetlin Nakov
 
Най-търсените направления в ИТ сферата за 2024
Най-търсените направления в ИТ сферата за 2024Най-търсените направления в ИТ сферата за 2024
Най-търсените направления в ИТ сферата за 2024
Svetlin Nakov
 
BG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учителиBG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учители
Svetlin Nakov
 
Programming World in 2024
Programming World in 2024Programming World in 2024
Programming World in 2024
Svetlin Nakov
 
AI Tools for Business and Startups
AI Tools for Business and StartupsAI Tools for Business and Startups
AI Tools for Business and Startups
Svetlin Nakov
 
AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)
Svetlin Nakov
 
AI Tools for Entrepreneurs
AI Tools for EntrepreneursAI Tools for Entrepreneurs
AI Tools for Entrepreneurs
Svetlin Nakov
 
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Svetlin Nakov
 
AI Tools for Business and Personal Life
AI Tools for Business and Personal LifeAI Tools for Business and Personal Life
AI Tools for Business and Personal Life
Svetlin Nakov
 
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин НаковДипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Svetlin Nakov
 
Дипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООПДипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООП
Svetlin Nakov
 
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТСвободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Svetlin Nakov
 
AI and the Professions of the Future
AI and the Professions of the FutureAI and the Professions of the Future
AI and the Professions of the Future
Svetlin Nakov
 
Programming Languages Trends for 2023
Programming Languages Trends for 2023Programming Languages Trends for 2023
Programming Languages Trends for 2023
Svetlin Nakov
 
IT Professions and How to Become a Developer
IT Professions and How to Become a DeveloperIT Professions and How to Become a Developer
IT Professions and How to Become a Developer
Svetlin Nakov
 
GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)
Svetlin Nakov
 
AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
Svetlin Nakov
 
AI за ежедневието - Наков @ Techniverse (Nov 2024)
AI за ежедневието - Наков @ Techniverse (Nov 2024)AI за ежедневието - Наков @ Techniverse (Nov 2024)
AI за ежедневието - Наков @ Techniverse (Nov 2024)
Svetlin Nakov
 
AI инструменти за бизнеса - Наков - Nov 2024
AI инструменти за бизнеса - Наков - Nov 2024AI инструменти за бизнеса - Наков - Nov 2024
AI инструменти за бизнеса - Наков - Nov 2024
Svetlin Nakov
 
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
Svetlin Nakov
 
Software Engineers in the AI Era - Sept 2024
Software Engineers in the AI Era - Sept 2024Software Engineers in the AI Era - Sept 2024
Software Engineers in the AI Era - Sept 2024
Svetlin Nakov
 
Най-търсените направления в ИТ сферата за 2024
Най-търсените направления в ИТ сферата за 2024Най-търсените направления в ИТ сферата за 2024
Най-търсените направления в ИТ сферата за 2024
Svetlin Nakov
 
BG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учителиBG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учители
Svetlin Nakov
 
Programming World in 2024
Programming World in 2024Programming World in 2024
Programming World in 2024
Svetlin Nakov
 
AI Tools for Business and Startups
AI Tools for Business and StartupsAI Tools for Business and Startups
AI Tools for Business and Startups
Svetlin Nakov
 
AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)
Svetlin Nakov
 
AI Tools for Entrepreneurs
AI Tools for EntrepreneursAI Tools for Entrepreneurs
AI Tools for Entrepreneurs
Svetlin Nakov
 
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Svetlin Nakov
 
AI Tools for Business and Personal Life
AI Tools for Business and Personal LifeAI Tools for Business and Personal Life
AI Tools for Business and Personal Life
Svetlin Nakov
 
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин НаковДипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Svetlin Nakov
 
Дипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООПДипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООП
Svetlin Nakov
 
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТСвободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Svetlin Nakov
 
AI and the Professions of the Future
AI and the Professions of the FutureAI and the Professions of the Future
AI and the Professions of the Future
Svetlin Nakov
 
Programming Languages Trends for 2023
Programming Languages Trends for 2023Programming Languages Trends for 2023
Programming Languages Trends for 2023
Svetlin Nakov
 
IT Professions and How to Become a Developer
IT Professions and How to Become a DeveloperIT Professions and How to Become a Developer
IT Professions and How to Become a Developer
Svetlin Nakov
 
GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)
Svetlin Nakov
 
Ad

Recently uploaded (20)

Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native BarcelonaOpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your wayPlooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native BarcelonaOpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your wayPlooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 

Java Foundations: Lists, ArrayList<T>

  • 3. The Judge System Sending your Solutions for Automated Evaluation
  • 4. Testing Your Code in the Judge System  Test your code online in the SoftUni Judge system: https://judge.softuni.org/Contests/3294
  • 5. Lists in Java Processing Variable Length Sequences of Elements
  • 6. Table of Contents 1. Lists: Overview 2. List Manipulating: Add, Delete, Insert, Clear 3. Reading Lists from the Console. Printing Lists 4. Sorting Lists and Arrays 7
  • 8. List<E> – Overview  List<E> holds a list of elements of any type 9 List<String> names = new ArrayList<>(); // Create a list of strings names.add("Peter"); names.add("Maria"); names.add("George"); names.remove("Maria"); for (String name : names) System.out.println(name); // Peter, George
  • 9. List<E> – Overview (2) 10 List<Integer> nums = new ArrayList<>( Arrays.asList(10, 20, 30, 40, 50, 60)); nums.remove(2); nums.remove(Integer.valueOf(40)); nums.add(100); nums.add(0, -100); for (int i = 0; i < nums.size(); i++) System.out.print(nums.get(i) + " "); -100 10 20 50 60 100 Inserts an element to index Items count Remove by index Remove by value (slow)
  • 10.  List<E> holds a list of elements (like array, but extendable)  Provides operations to add / insert / remove / find elements:  size() – number of elements in the List<E>  add(element) – adds an element to the List<E>  add(index, element) – inserts an element to given position  remove(element) – removes an element (returns true / false)  remove(index) – removes element at index  contains(element) – determines whether an element is in the list  set(index, item) – replaces the element at the given index List<E> – Data Structure 11
  • 11. add – Appends an Element 12 10 5 2 0 Count: 1 2 3 List<Integer> 10 5 2
  • 12. 10 remove – Deletes an Element 13 2 5 Count: List<Integer> 10 2 3 10
  • 13. add (index, el) – Inserts an Element at Position 14 3 2 2 5 Count: List<Integer> -5 -5
  • 14. Reading Lists from the Console Using for Loop or String.split() 15
  • 15.  First, read from the console the array length:  Next, create a list of given size n and read its elements: Reading Lists From the Console Scanner sc = new Scanner(System.in); int n = Integer.parseInt(sc.nextLine()); List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int number = Integer.parseInt(sc.nextLine()); list.add(number); }
  • 16.  Lists can be read from a single line of space separated values: Reading List Values from a Single Line 17 2 8 30 25 40 72 -2 44 56 String values = sc.nextLine(); List<String> items = Arrays.stream(values.split(" ")) .collect(Collectors.toList()); List<Integer> nums = new ArrayList<>(); for (int i = 0; i < items.size(); i++) nums.add(Integer.parseInt(items.get(i))); Convert a collection into List List<Integer> items = Arrays.stream(values.split(" ")) .map(Integer::parseInt).collect(Collectors.toList());
  • 17.  Printing a list using a for-loop:  Printing a list using a String.join(): Printing Lists on the Console 18 List<String> list = new ArrayList<>(Arrays.asList( "one", "two", "three", "four", "five", "six")); for (int index = 0; index < list.size(); index++) System.out.printf ("arr[%d] = %s%n", index, list.get(index)); List<String> list = new ArrayList<>(Arrays.asList( "one", "two", "three", "four", "five", "six")); System.out.println(String.join("; ", list)); Gets an element at given index
  • 18.  Write a program to sum all adjacent equal numbers in a list of decimal numbers, starting from left to right  Examples: Problem: Sum Adjacent Equal Numbers 19 3 3 6 1 12 1 8 2 2 4 8 16 16 8 16 5 4 2 1 1 4 5 8 4
  • 19. Scanner sc = new Scanner(System.in); List<Double> numbers = Arrays.stream(sc.nextLine().split(" ")) .map(Double::parseDouble).collect(Collectors.toList()); for (int i = 0; i < numbers.size() - 1; i++) if (numbers.get(i).equals(numbers.get(i + 1))) { numbers.set(i, numbers.get(i) + numbers.get(i + 1)); numbers.remove(i + 1); i = -1; } // Continues on the next slide Solution: Sum Adjacent Equal Numbers (1) 0
  • 20. Solution: Sum Adjacent Equal Numbers (2) 21 static String joinElementsByDelimiter (List<Double> items, String delimiter) { String output = ""; for (Double item : items) output += (new DecimalFormat("0.#").format(item) + delimiter); return output; } String output = joinElementsByDelimiter(numbers, " "); System.out.println(output);
  • 21.  Write a program that sums all numbers in a list in the following order:  first + last, first + 1 + last - 1, first + 2 + last - 2, … first + n, last – n  Examples: Problem: Gauss' Trick 22 1 2 3 4 5 6 6 3 1 2 3 4 5 5
  • 22. Solution: Gauss' Trick 3 Scanner sc = new Scanner(System.in); List<Integer> numbers = Arrays.stream(sc.nextLine().split(" ")) .map(Integer::parseInt).collect(Collectors.toList()); int size = numbers.size(); for (int i = 0; i < size / 2; i++) { numbers.set(i, numbers.get(i) + numbers.get(numbers.size() - 1)); numbers.remove(numbers.size() - 1); } System.out.println(numbers.toString().replaceAll("[[],]", ""));
  • 23.  You receive two lists with numbers. Print a result list which contains the numbers from both lists  If the length of the two lists is not equal, just add the remaining elements at the end of the list  list1[0], list2[0], list1[1], list2[1], … Problem: Merging Lists 24 1 2 3 4 5 6 7 8 1 6 2 7 3 8 4 5
  • 24. // TODO: Read the input List<Integer> resultNums = new ArrayList<>(); for (int i = 0; i < Math.min(nums1.size(), nums2.size()); i++) { // TODO: Add numbers in resultNums } if (nums1.size() > nums2.size()) resNums.addAll(getRemainingElements(nums1, nums2)); else if (nums2.size() > nums1.size()) resNums.addAll(getRemainingElements(nums2, nums1)); System.out.println(resNums.toString().replaceAll("[[],]", "")); Solution: Merging Lists (1) 25
  • 25. public static List<Integer> getRemainingElements (List<Integer> longerList, List<Integer> shorterList) { List<Integer> nums = new ArrayList<>(); for (int i = shorterList.size(); i < longerList.size(); i++) nums.add(longerList.get(i)); return nums; } Solution: Merging Lists (2) 26
  • 26. Live Exercises Reading and Manipulating Lists
  • 27. Sorting Lists and Arrays 28
  • 28.  Sorting a list == reorder its elements incrementally: Sort()  List items should be comparable, e.g. numbers, strings, dates, … Sorting Lists List<String> names = new ArrayList<>(Arrays.asList( "Peter", "Michael", "George", "Victor", "John")); Collections.sort(names); System.out.println(String.join(", ", names)); // George, John, Michael, Peter, Victor Collections.sort(names); Collections.reverse(names); System.out.println(String.join(", ", names)); // Victor, Peter, Michael, John, George Sort in natural (ascending) order Reverse the sorted result
  • 29.  Read a number n and n lines of products. Print a numbered list of all the products ordered by name  Examples: Problem: List of Products 30 4 Potatoes Tomatoes Onions Apples 1.Apples 2.Onions 3.Potatoes 4.Tomatoes A Z
  • 30. int n = Integer.parseInt(sc.nextLine()); List<String> products = new ArrayList<>(); for (int i = 0; i < n; i++) { String currentProduct = sc.nextLine(); products.add(currentProduct); } Collections.sort(products); for (int i = 0; i < products.size(); i++) System.out.printf("%d.%s%n", i + 1, products.get(i)); Solution: List of Products
  • 31.  Read a list of integers, remove all negative numbers from it  Print the remaining elements in reversed order  In case of no elements left in the list, print "empty" Problem: Remove Negatives and Reverse 32 10 -5 7 9 -33 50 50 9 7 10 7 -2 -10 1 1 7 -1 -2 -3 empty
  • 32. List<Integer> nums = Arrays.stream(sc.nextLine().split(" ")) .map(Integer::parseInt).collect(Collectors.toList()); for (int i = 0; i < nums.size(); i++) if (nums.get(i) < 0) nums.remove(i--); Collections.reverse(nums); if (nums.size() == 0) System.out.println("empty"); else System.out.println(nums.toString().replaceAll("[[],]", "")); Solution: Remove Negatives and Reverse
  • 34.  …  …  … Summary 35  Lists hold a sequence of elements (variable-length)  Can add / remove / insert elements at runtime  Creating (allocating) a list: new ArrayList<E>()  Accessing list elements by index  Printing list elements: String.join(…)
  • 35.  …  …  … Next Steps  Join the SoftUni "Learn To Code" Community  Access the Free Coding Lessons  Get Help from the Mentors  Meet the Other Learners https://softuni.org

Editor's Notes

  • #2: Hello, I am Svetlin Nakov from SoftUni (the Software University). Together with my colleague George Georgiev, we shall teach this free Java Foundations course, which covers important concepts from Java programming, such as arrays, lists, methods, strings, classes, objects and exceptions, and prepares you for the "Java Foundations" official exam from Oracle. In this lesson your instructor George will explain and demonstrate how to use lists in Java, how to allocate a list using the ArrayList generic class, how to access list elements by index, how to add, modify, insert, and delete elements from list and how to read, traverse and print a list. Lists in Java are like arrays: they hold an indexed sequence of elements of the same type. But unlike arrays, lists can resize. In this tutorial on Java arrays, along with the live coding examples, your instructor George will give you some hands-on exercises to gain practical experience. Are you ready? Let's start!
  • #3: Before the start, I would like to introduce your course instructors: Svetlin Nakov and George Georgiev, who are experienced Java developers, senior software engineers and inspirational tech trainers. They have spent thousands of hours teaching programming and software technologies and are top trainers from SoftUni. I am sure you will like how they teach programming.
  • #4: Most of this course will be taught by George Georgiev, who is a senior software engineer with many years of experience with Java, JavaScript and C++. George enjoys teaching programming very much and is one of the top trainers at the Software University, having delivered over 300 technical training sessions on the topics of data structures and algorithms, Java essentials, Java fundamentals, C++ programming, C# development and many others. I have no doubt you will benefit greatly from his lessons, as he always does his best to explain the most challenging concepts in a simple and fun way.
  • #5: Before we dive into the course, I want to show you the SoftUni judge system, where you can get instant feedback for your exercise solutions. SoftUni Judge is an automated system for code evaluation. You just send your code for a certain coding problem and the system will tell you whether your solution is correct or not and what exactly is missing or wrong. I am sure you will love the judge system, once you start using it!
  • #6: // Solution to problem "01. Student Information". import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String name = sc.nextLine(); int age = Integer.parseInt(sc.nextLine()); double grade = Double.parseDouble(sc.nextLine()); System.out.printf("Name: %s, Age: %d, Grade: %.2f", name, age, grade); } }
  • #7: In this section your instructor George will explain the concept of "Lists in Java" and how to use the ArrayList class. Lists in Java are like arrays, but they can change their size. You can add, modify, insert and delete elements from a list. Lists hold indexed sequence of elements, which can be freely modified. Let's learn how to use lists in Java and solve a few hands-on exercises to gain experience in processing sequences of elements.
  • #37: Did you like this lesson? Do you want more? Join the learners' community at softuni.org. Subscribe to my YouTube channel to get more free video tutorials on coding and software development. Get free access to the practical exercises and the automated judge system for this coding lesson. Get free help from mentors and meet other learners. Join now! It's free. SOFTUNI.ORG