Bạn đang xem: Duyệt arraylist trong java

Một ArrayList là một mảng rất có thể resize, còn được gọi là một mảng đụng.Nó tăng size của nó nhằm chứa những bộ phận new với thu nhỏ tuổi size Lúc các phần tử được loại bỏ.
ArrayList bên trong sử dụng một mảng để lưu trữ những bộ phận.Giống như mảng, Nó cho phép các bạn đem các phần tử theo chỉ mục của chúng.
Xem thêm: Bài 1 : Abstract Noun Là Gì, Nghĩa Của Từ Abstract Noun Trong Tiếng Việt
import java.util.ArrayList;import java.util.List;public class CreateArrayListExample public static void main(String<> args) // Creating an ArrayList of String ListString> animals = new ArrayList>(); // Adding new elements to lớn the ArrayList animals.add("Lion"); animals.add("Tiger"); animals.add("Cat"); animals.add("Dog"); System.out.println(animals); // Adding an element at a particular index in an ArrayList animals.add(2, "Elephant"); System.out.println(animals); # Output
2. Tạo một ArrayList từ Collection khác
import java.util.ArrayList;import java.util.List;public class CreateArrayListFromCollectionExample public static void main(String<> args) ListInteger> firstFivePrimeNumbers = new ArrayList>(); firstFivePrimeNumbers.add(2); firstFivePrimeNumbers.add(3); firstFivePrimeNumbers.add(5); firstFivePrimeNumbers.add(7); firstFivePrimeNumbers.add(11); // Creating an ArrayList from another collection ListInteger> firstTenPrimeNumbers = new ArrayList>(firstFivePrimeNumbers); ListInteger> nextFivePrimeNumbers = new ArrayList>(); nextFivePrimeNumbers.add(13); nextFivePrimeNumbers.add(17); nextFivePrimeNumbers.add(19); nextFivePrimeNumbers.add(23); nextFivePrimeNumbers.add(29); // Adding an entire collection to lớn an ArrayList firstTenPrimeNumbers.addAll(nextFivePrimeNumbers); System.out.println(firstTenPrimeNumbers); # Output<2, 3, 5, 7, 11, 13, 17, 19, 23, 29>
3. Truy cập những bộ phận từ 1 ArrayList
import java.util.ArrayList;import java.util.List;public class AccessElementsFromArrayListExample public static void main(String<> args) ListString> topCompanies = new ArrayList>(); // Cheông chồng if an ArrayList is empty System.out.println("Is the topCompanies menu empty? : " + topCompanies.isEmpty()); topCompanies.add("Google"); topCompanies.add("Apple"); topCompanies.add("Microsoft"); topCompanies.add("Amazon"); topCompanies.add("Facebook"); // Find the kích thước of an ArrayList System.out.println("Here are the top " + topCompanies.size() + " companies in the world"); System.out.println(topCompanies); // Retrieve sầu the element at a given index String bestCompany = topCompanies.get(0); String secondBestCompany = topCompanies.get(1); String lastCompany = topCompanies.get(topCompanies.size() - 1); System.out.println("Best Company: " + bestCompany); System.out.println("Second Best Company: " + secondBestCompany); System.out.println("Last Company in the list: " + lastCompany); // Modify the element at a given index topCompanies.set(4, "Walmart"); System.out.println("Modified top companies list: " + topCompanies); # OutputIs the topCompanies menu empty? : trueHere are the top 5 companies in the world
4. Xóa các bộ phận khỏi một ArrayList
import java.util.ArrayList;import java.util.List;public class RemoveElementsFromArrayListExample public static void main(String<> args) ListString> programmingLanguages = new ArrayList>(); programmingLanguages.add("C"); programmingLanguages.add("C++"); programmingLanguages.add("Java"); programmingLanguages.add("Kotlin"); programmingLanguages.add("Python"); programmingLanguages.add("Perl"); programmingLanguages.add("Ruby"); System.out.println("Initial List: " + programmingLanguages); // Remove sầu the element at index `5` programmingLanguages.remove(5); System.out.println("After remove(5): " + programmingLanguages); // Remove sầu the first occurrence of the given element from the ArrayList // (The remove() method returns false if the element does not exist in the ArrayList) boolean isRemoved = programmingLanguages.remove("Kotlin"); System.out.println("After remove("Kotlin"): " + programmingLanguages); // Remove all the elements that exist in a given collection ListString> scriptingLanguages = new ArrayList>(); scriptingLanguages.add("Python"); scriptingLanguages.add("Ruby"); scriptingLanguages.add("Perl"); programmingLanguages.removeAll(scriptingLanguages); System.out.println("After removeAll(scriptingLanguages): " + programmingLanguages); // Remove sầu all the elements that satisfy the given predicate programmingLanguages.removeIf(n -> (n.charAt(0) == "T")); /* The above removeIf() Gọi can also be written using lambda expression like this - programmingLanguages.removeIf(s -> s.startsWith("C")) */ System.out.println("After Removing all elements that start with "C": " + programmingLanguages); // Remove all elements from the ArrayList programmingLanguages.clear(); System.out.println("After clear(): " + programmingLanguages); # OutputInitial List:
5. Duyệt qua những bộ phận trong ArrayList
Vòng lặp for-eachVòng lặp cùng với chỉ sốimport java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.ListIterator;public class IterateOverArrayListExample public static void main(String<> args) ListString> tvShows = new ArrayList>(); tvShows.add("Breaking Bad"); tvShows.add("trò chơi Of Thrones"); tvShows.add("Friends"); tvShows.add("Prison break"); System.out.println("=== Iterate using Java 8 forEach và lambdomain authority ==="); tvShows.forEach(tvShow -> System.out.println(tvShow); ); System.out.println(" === Iterate using an iterator() ==="); IteratorString> tvShowIterator = tvShows.iterator(); while (tvShowIterator.hasNext()) String tvShow = tvShowIterator.next(); System.out.println(tvShow); System.out.println(" === Iterate using a listIterator() to lớn traverse in both directions ==="); // Here, we start from the kết thúc of the menu and traverse backwards. ListIteratorString> tvShowListIterator = tvShows.listIterator(tvShows.size()); while (tvShowListIterator.hasPrevious()) String tvShow = tvShowListIterator.previous(); System.out.println(tvShow); System.out.println(" === Iterate using simple for-each loop ==="); for(String tvShow: tvShows) System.out.println(tvShow); System.out.println(" === Iterate using for loop with index ==="); for(int i = 0; i tvShows.size(); i++) System.out.println(tvShows.get(i)); # Output=== Iterate using Java 8 forEach và lambdomain authority ===Breaking BadGame Of ThronesFriendsPrison break=== Iterate using an iterator() ===Breaking Badtrò chơi Of ThronesFriendsPrison break=== Iterate using a listIterator() khổng lồ traverse in both directions ===Prison breakFriendstrò chơi Of ThronesBreaking Bad=== Iterate using simple for-each loop ===Breaking Badtrò chơi Of ThronesFriendsPrison break=== Iterate using for loop with index ===Breaking Badtrò chơi Of ThronesFriendsPrison break
Cácpmùi hương thứciterator()vàlistIterator()hữu dụng khi chúng ta đề nghị sửa đổi ArrayList trong lúc chú tâm qua các bộ phận.
Hãy chu đáo ví dụ sau, trong các số ấy họ đang sa thải các thành phần khỏi ArrayList bằng phương pháp thực hiện pmùi hương thứciterator.remove()trong lúc chú tâm qua nó:
import java.util.ArrayList;import java.util.Iterator;import java.util.List;public class ArrayListIteratorRemoveExample public static void main(String<> args) ListInteger> numbers = new ArrayList>(); numbers.add(13); numbers.add(18); numbers.add(25); numbers.add(40); IteratorInteger> numbersIterator = numbers.iterator(); while (numbersIterator.hasNext()) Integer num = numbersIterator.next(); if(num % 2 != 0) numbersIterator.remove(); System.out.println(numbers); # Output<18, 40>
6. Tìm kiếm các thành phần trong một ArrayList
import java.util.ArrayList;import java.util.List;public class SearchElementsInArrayListExample public static void main(String<> args) ListString> names = new ArrayList>(); names.add("John"); names.add("Alice"); names.add("Bob"); names.add("Steve"); names.add("John"); names.add("Steve"); names.add("Maria"); // Check if an ArrayList contains a given element System.out.println("Does names array contain "Bob"? : " + names.contains("Bob")); // Find the index of the first occurrence of an element in an ArrayList System.out.println("indexOf "Steve": " + names.indexOf("Steve")); System.out.println("indexOf "Mark": " + names.indexOf("Mark")); // Find the index of the last occurrence of an element in an ArrayList System.out.println("lastIndexOf "John" : " + names.lastIndexOf("John")); System.out.println("lastIndexOf "Bill" : " + names.lastIndexOf("Bill")); # OutputDoes names array contain "Bob"? : trueindexOf "Steve": 3indexOf "Mark": -1lastIndexOf "John" : 4lastIndexOf "Bill" : -1
7. ArrayList của những đối tượng người dùng bởi người tiêu dùng định nghĩa
Vì ArrayList cung cấp generic, bạn có thể tạo ra ArrayList thuộcbất kỳloạilàm sao.Nó có thể là các nhiều loại dễ dàng và đơn giản như thếInteger,String,Doublehoặc những các loại phức hợp nlỗi một ArrayList của ArrayLists, hoặc một ArrayList của HashMaps hoặc một ArrayList của bất kỳ người tiêu dùng tư tưởng những đối tượng người dùng.
import java.util.ArrayList;import java.util.List;class User private String name; private int age; public User(String name, int age) this.name = name; this.age = age; public String getName() return name; public void setName(String name) this.name = name; public int getAge() return age; public void setAge(int age) this.age = age; public class ArrayListUserDefinedObjectExample public static void main(String<> args) ListUser> users = new ArrayList>(); users.add(new User("Rajeev", 25)); users.add(new User("John", 34)); users.add(new User("Steve", 29)); users.forEach(user -> System.out.println("Name : " + user.getName() + ", Age : " + user.getAge()); ); # OutputName : Rajeev, Age : 25Name : John, Age : 34Name : Steve sầu, Age : 29
8. Sắp xếp một ArrayList
Sắp xếp một ArrayList là 1 trọng trách khôn cùng phổ biến nhưng bạn sẽ gặp trong số lịch trình của bản thân.Trong phần này, tôi sẽ chỉ cho mình bí quyết -
Sắp xếp một ArrayList của những đối tượng người dùng vì người dùng xác minh bởi một cỗ đối chiếu thiết lập.8.1. Sắp xếp một ArrayList bởi thủ tục Collections.sort ()import java.util.ArrayList;import java.util.Collections;import java.util.List;public class ArrayListCollectionsSortExample public static void main(String<> args) ListInteger> numbers = new ArrayList>(); numbers.add(13); numbers.add(7); numbers.add(18); numbers.add(5); numbers.add(2); System.out.println("Before : " + numbers); // Sorting an ArrayList using Collections.sort() method Collections.sort(numbers); System.out.println("After : " + numbers); # OutputBefore : <13, 7, 18, 5, 2>After : <2, 5, 7, 13, 18>8.2 Sắp xếp một ArrayList bằng cách thức ArrayList.sort ()import java.util.ArrayList;import java.util.Comparator;import java.util.List;public class ArrayListSortExample public static void main(String<> args) ListString> names = new ArrayList>(); names.add("Lisa"); names.add("Jennifer"); names.add("Mark"); names.add("David"); System.out.println("Names : " + names); // Sort an ArrayList using its sort() method. You must pass a Comparator lớn the ArrayList.sort() method. names.sort(new ComparatorString>()
Override public int compare(String name1, String name2) return name1.compareTo(name2); ); // The above `sort()` method Call can also be written simply using lambda expression names.sort((name1, name2) -> name1.compareTo(name2)); // Following is an even more concise solution names.sort(Comparator.naturalOrder()); System.out.println("Sorted Names : " + names); # OutputNames :
Override public String toString() return "" + "name="" + name + """ + ", age=" + age + ""; public class ArrayListObjectSortExample public static void main(String<> args) ListPerson> people = new ArrayList>(); people.add(new Person("Sachin", 47)); people.add(new Person("Chris", 34)); people.add(new Person("Rajeev", 25)); people.add(new Person("David", 31)); System.out.println("Person List : " + people); // Sort People by their Age people.sort((person1, person2) -> return person1.getAge() - person2.getAge(); ); // A more concise way of writing the above sầu sorting function people.sort(Comparator.comparingInt(Person::getAge)); System.out.println("Sorted Person List by Age : " + people); // You can also sort using Collections.sort() method by passing the custom Comparator Collections.sort(people, Comparator.comparing(Person::getName)); System.out.println("Sorted Person List by Name : " + people); # OutputPerson List :
Phần kết luận
Đó là tất cả những sản phẩm tôi share về ArrayList vào Java.Trong nội dung bài viết này, bạn sẽ tìm hiểu ArrayList là gì, cách chế tạo ArrayList, cách thêm, sửa đổi với xóa các thành phần khỏi ArrayList, bí quyết lặp qua ArrayList, phương pháp thu xếp ArrayList và phương pháp đồng hóa hóa quyền truy vấn vào ArrayList .