J
Collections
Java Syntax Guide
Arbeiten mit Datenstrukturen wie ArrayList und HashMap
Collections
Arbeiten mit Datenstrukturen wie ArrayList und HashMap
Java collections (java)
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
// ArrayList - dynamic array
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println("Names: " + names);
System.out.println("First name: " + names.get(0));
// LinkedList - doubly linked list
List<Integer> numbers = new LinkedList<>();
numbers.add(10);
numbers.add(20);
numbers.addFirst(5);
numbers.addLast(30);
// HashSet - unique elements
Set<String> uniqueNames = new HashSet<>();
uniqueNames.add("Alice");
uniqueNames.add("Bob");
uniqueNames.add("Alice"); // Duplicate, won't be added
System.out.println("Unique names: " + uniqueNames);
// HashMap - key-value pairs
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
ages.put("Charlie", 35);
System.out.println("Alice's age: " + ages.get("Alice"));
// Iterating over collections
System.out.println("All ages:");
for (Map.Entry<String, Integer> entry : ages.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Enhanced for loop
System.out.println("All names:");
for (String name : names) {
System.out.println(name);
}
// Using streams (Java 8+)
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println("Even numbers: " + evenNumbers);
// Sorting
Collections.sort(names);
System.out.println("Sorted names: " + names);
// Queue and Stack
Queue<String> queue = new LinkedList<>();
queue.offer("First");
queue.offer("Second");
System.out.println("Queue poll: " + queue.poll());
Deque<String> stack = new ArrayDeque<>();
stack.push("Bottom");
stack.push("Top");
System.out.println("Stack pop: " + stack.pop());
}
}
Explanation
Das Java Collections Framework bietet eine einheitliche Architektur zur Darstellung und Manipulation von Collections, einschließlich Listen (wie ArrayList) und Maps (wie HashMap).
Common Use Cases
- Speichern und Verwalten von Objektgruppen
- Effiziente Datenabfrage
- Implementieren verschiedener Datenstrukturen
Related Java Syntax
Master Collections in Java
Understanding Collections is fundamental to writing clean and efficient Java code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.
Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using Collections effectively in your Java projects.
Key Takeaways
- Speichern und Verwalten von Objektgruppen
- Effiziente Datenabfrage
- Implementieren verschiedener Datenstrukturen