一、List基礎知識
Java中的List是一個有序的集合,它允許我們在集合中插入、查找、刪除元素。List中可以存放任意類型的對象,包括String、Integer、Double等等。
為了使用List,我們需要先導入List類所在的包:java.util。接下來,我們可以創建一個空的List對象,例如:
List list = new ArrayList();
這樣就創建了一個String類型的List對象。
接下來,我們可以向List中添加元素:
list.add("apple"); list.add("banana"); list.add("orange");
通過List的add()方法向其中添加元素。List中的元素是按照插入順序存儲的,所以元素的順序同添加的順序一致。
二、List的查找
1、使用indexOf()方法查找元素
我們可以使用List的indexOf()方法查找某個元素在List中的位置,例如:
int index = list.indexOf("banana"); System.out.println("banana在List中的位置是:" + index);
這裡通過indexOf()方法查找”banana”在List中的位置。
2、使用contains()方法查找元素是否存在
我們還可以使用List的contains()方法判斷某個元素是否在List中存在,例如:
boolean hasApple = list.contains("apple"); System.out.println("List中是否存在apple:" + hasApple);
這裡通過contains()方法判斷”apple”是否存在於List中。
3、使用filter過濾元素
另一種查找元素的方式是使用filter方法,它可以根據特定條件篩選出符合條件的元素。例如,我們可以篩選出長度為3的單詞:
List resultList = list.stream().filter(s -> s.length() == 3).collect(Collectors.toList()); for (String word : resultList) { System.out.println(word); }
在這個例子中,我們使用了Java 8中的Lambda表達式來定義篩選條件,filter()方法會根據這個條件對List中的元素進行篩選,並將符合條件的元素放入resultList中。
三、List的排序
1、使用Collections.sort()方法排序
Collections是Java中常用的工具類,其中包括了對集合進行排序的方法。我們可以使用Collections.sort()方法對List進行排序,例如:
List numbers = new ArrayList(); numbers.add(5); numbers.add(3); numbers.add(8); numbers.add(2); Collections.sort(numbers); for (Integer number : numbers) { System.out.println(number); }
這個例子中,我們使用Collections.sort()方法對List中的整數進行排序,並輸出排序後的結果。
2、使用Comparator.comparing()方法排序
Java 8中新增了一種排序方式,使用Comparator.comparing()方法進行對象的排序。例如,我們可以對Person對象按照年齡排序:
class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } List people = new ArrayList(); people.add(new Person("David", 28)); people.add(new Person("Alice", 25)); people.add(new Person("Bob", 30)); Collections.sort(people, Comparator.comparing(Person::getAge)); for (Person person : people) { System.out.println(person.getName() + " " + person.getAge()); }
在這個例子中,我們定義了一個Person類,包含姓名和年齡兩個屬性。使用Comparator.comparing()方法可以對List中的Person對象按照年齡進行排序。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/182375.html