🎯 Exemplos recomendados
Balanced sample collections from various categories for you to explore
Exemplos de Estruturas de Dados Android Java
Exemplos de estruturas de dados Android Java incluindo operações comuns com arrays, tabelas hash e listas ligadas
💻 Operações de Array java
🟢 simple
⭐⭐⭐
Realizar operações comuns de array incluindo adicionar, remover, atualizar, pesquisar e ordenar usando coleções Java
⏱️ 30 min
🏷️ java, android, data structures, arrays
Prerequisites:
Basic Java knowledge, Collections framework
// Android Java Array Operations Examples
// Using Lists, Arrays, and ArrayList
import java.util.*;
// 1. Basic Array Operations
public class BasicArrayOperations {
// Create and initialize arrays
public void createArrays() {
// Using ArrayList (mutable)
List<Integer> arrayList = new ArrayList<>();
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(4);
arrayList.add(5);
System.out.println("ArrayList: " + arrayList);
// Using Arrays (fixed size)
int[] array = {1, 2, 3, 4, 5};
System.out.println("Array: " + Arrays.toString(array));
// Using LinkedList
List<Integer> linkedList = new LinkedList<>();
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);
linkedList.add(4);
linkedList.add(5);
System.out.println("LinkedList: " + linkedList);
// Create from existing collection
List<Integer> listFromArray = new ArrayList<>();
for (int num : array) {
listFromArray.add(num);
}
System.out.println("List from array: " + listFromArray);
}
// Access elements
public void accessElements(List<Integer> list) {
System.out.println("First element: " + list.get(0));
System.out.println("Last element: " + list.get(list.size() - 1));
System.out.println("Element at index 2: " + list.get(2));
// Safe access
if (list.size() > 10) {
System.out.println("Element at index 10: " + list.get(10));
} else {
System.out.println("Element at index 10: Index out of bounds");
}
}
// Check element existence
public void checkElement(List<Integer> list, int element) {
System.out.println("Contains " + element + ": " + list.contains(element));
System.out.println("Index of " + element + ": " + list.indexOf(element));
System.out.println("Last index of " + element + ": " + list.lastIndexOf(element));
}
// Get array size
public void getSize(List<Integer> list) {
System.out.println("Size: " + list.size());
System.out.println("Is empty: " + list.isEmpty());
}
}
// 2. Mutable Array Operations
public class MutableArrayOperations {
// Add elements
public void addElements() {
List<Integer> list = new ArrayList<>();
// Add single element
list.add(1);
list.add(2);
System.out.println("After adding: " + list);
// Add at specific index
list.add(1, 10);
System.out.println("After insert at index 1: " + list);
// Add all from another collection
List<Integer> moreNumbers = new ArrayList<>();
moreNumbers.add(20);
moreNumbers.add(30);
moreNumbers.add(40);
list.addAll(moreNumbers);
System.out.println("After addAll: " + list);
// Add at index from another collection
List<Integer> atStart = new ArrayList<>();
atStart.add(100);
atStart.add(200);
list.addAll(2, atStart);
System.out.println("After addAll at index: " + list);
}
// Remove elements
public void removeElements() {
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 3, 6));
// Remove by value (first occurrence)
list.remove(Integer.valueOf(3));
System.out.println("After remove(3): " + list);
// Remove by index
list.remove(2);
System.out.println("After removeAt(2): " + list);
// Remove first occurrence
list.remove(Integer.valueOf(3));
System.out.println("After remove first 3: " + list);
// Remove all matching
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
numbers.removeAll(Arrays.asList(2, 4));
System.out.println("After removeAll(2,4): " + numbers);
// Remove range using subList
List<Integer> rangeList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
rangeList.subList(2, 5).clear();
System.out.println("After remove range 2-5: " + rangeList);
// Clear all
rangeList.clear();
System.out.println("After clear: " + rangeList);
}
// Update elements
public void updateElements() {
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
// Update by index
list.set(2, 30);
System.out.println("After update index 2: " + list);
// Update in place
for (int i = 0; i < list.size(); i++) {
list.set(i, list.get(i) * 10);
}
System.out.println("After in-place update: " + list);
// Replace all
List<Integer> newList = new ArrayList<>();
for (int num : list) {
newList.add(num * 2);
}
System.out.println("After map * 2: " + newList);
}
}
// 3. Array Searching
public class ArraySearching {
// Linear search
public int linearSearch(List<Integer> list, int target) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == target) {
return i;
}
}
return -1;
}
// Binary search (requires sorted list)
public int binarySearch(List<Integer> list, int target) {
int left = 0;
int right = list.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (list.get(mid) == target) {
return mid;
} else if (list.get(mid) < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
// Find max and min
public int[] findMaxMin(List<Integer> list) {
if (list.isEmpty()) return null;
int max = list.get(0);
int min = list.get(0);
for (int element : list) {
if (element > max) max = element;
if (element < min) min = element;
}
return new int[]{max, min};
}
// Find duplicates
public List<Integer> findDuplicates(List<Integer> list) {
Set<Integer> seen = new HashSet<>();
Set<Integer> duplicates = new HashSet<>();
for (int element : list) {
if (!seen.add(element)) {
duplicates.add(element);
}
}
return new ArrayList<>(duplicates);
}
// Count occurrences
public int countOccurrences(List<Integer> list, int target) {
int count = 0;
for (int element : list) {
if (element == target) {
count++;
}
}
return count;
}
}
// 4. Array Sorting
public class ArraySorting {
// Built-in sort ascending
public void sortAscending(List<Integer> list) {
Collections.sort(list);
}
// Built-in sort descending
public void sortDescending(List<Integer> list) {
Collections.sort(list, Collections.reverseOrder());
}
// Sort by custom comparator
public void sortCustom(List<String> list) {
// Sort by length
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return Integer.compare(s1.length(), s2.length());
}
});
}
// Bubble sort (manual implementation)
public void bubbleSort(List<Integer> arr) {
int n = arr.size();
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr.get(j) > arr.get(j + 1)) {
// Swap
int temp = arr.get(j);
arr.set(j, arr.get(j + 1));
arr.set(j + 1, temp);
}
}
}
}
// Selection sort
public void selectionSort(List<Integer> arr) {
int n = arr.size();
for (int i = 0; i < n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++) {
if (arr.get(j) < arr.get(minIdx)) {
minIdx = j;
}
}
// Swap
int temp = arr.get(minIdx);
arr.set(minIdx, arr.get(i));
arr.set(i, temp);
}
}
// Quick sort
public void quickSort(List<Integer> arr, int low, int high) {
if (low < high) {
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
private int partition(List<Integer> arr, int low, int high) {
int pivot = arr.get(high);
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr.get(j) <= pivot) {
i++;
// Swap arr[i] and arr[j]
int temp = arr.get(i);
arr.set(i, arr.get(j));
arr.set(j, temp);
}
}
// Swap arr[i+1] and arr[high]
int temp = arr.get(i + 1);
arr.set(i + 1, arr.get(high));
arr.set(high, temp);
return i + 1;
}
}
// 5. Array Filtering and Mapping
public class ArrayTransformations {
// Filter elements
public List<Integer> filterEven(List<Integer> list) {
List<Integer> result = new ArrayList<>();
for (int num : list) {
if (num % 2 == 0) {
result.add(num);
}
}
return result;
}
public List<Integer> filterGreaterThan(List<Integer> list, int threshold) {
List<Integer> result = new ArrayList<>();
for (int num : list) {
if (num > threshold) {
result.add(num);
}
}
return result;
}
// Map elements
public List<Integer> doubleElements(List<Integer> list) {
List<Integer> result = new ArrayList<>();
for (int num : list) {
result.add(num * 2);
}
return result;
}
public List<String> toStringList(List<Integer> list) {
List<String> result = new ArrayList<>();
for (int num : list) {
result.add("Number: " + num);
}
return result;
}
// Sum
public int sum(List<Integer> list) {
int total = 0;
for (int num : list) {
total += num;
}
return total;
}
// Product
public int product(List<Integer> list) {
int result = 1;
for (int num : list) {
result *= num;
}
return result;
}
// Join to string
public String joinToString(List<Integer> list, String delimiter) {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < list.size(); i++) {
if (i > 0) sb.append(delimiter);
sb.append(list.get(i));
}
sb.append("]");
return sb.toString();
}
// Partition
public Map<String, List<Integer>> partitionEvenOdd(List<Integer> list) {
Map<String, List<Integer>> result = new HashMap<>();
List<Integer> even = new ArrayList<>();
List<Integer> odd = new ArrayList<>();
for (int num : list) {
if (num % 2 == 0) {
even.add(num);
} else {
odd.add(num);
}
}
result.put("even", even);
result.put("odd", odd);
return result;
}
// Group by length
public Map<Integer, List<String>> groupByLength(List<String> list) {
Map<Integer, List<String>> result = new HashMap<>();
for (String s : list) {
int len = s.length();
if (!result.containsKey(len)) {
result.put(len, new ArrayList<>());
}
result.get(len).add(s);
}
return result;
}
// Chunk
public List<List<Integer>> chunkList(List<Integer> list, int size) {
List<List<Integer>> chunks = new ArrayList<>();
for (int i = 0; i < list.size(); i += size) {
int end = Math.min(i + size, list.size());
chunks.add(new ArrayList<>(list.subList(i, end)));
}
return chunks;
}
}
// Main demonstration
public class ArrayOperationsDemo {
public static void demonstrateArrayOperations() {
System.out.println("=== Android Java Array Operations Examples ===\n");
// 1. Basic operations
System.out.println("--- 1. Basic Array Operations ---");
BasicArrayOperations basicOps = new BasicArrayOperations();
basicOps.createArrays();
List<Integer> sampleList = new ArrayList<>(Arrays.asList(10, 20, 30, 40, 50));
basicOps.accessElements(sampleList);
basicOps.checkElement(sampleList, 30);
basicOps.getSize(sampleList);
// 2. Mutable operations
System.out.println("\n--- 2. Mutable Array Operations ---");
MutableArrayOperations mutableOps = new MutableArrayOperations();
mutableOps.addElements();
mutableOps.removeElements();
mutableOps.updateElements();
// 3. Searching
System.out.println("\n--- 3. Array Searching ---");
ArraySearching searching = new ArraySearching();
List<Integer> searchList = new ArrayList<>(Arrays.asList(1, 5, 3, 9, 2, 8, 7));
System.out.println("Linear search for 9: " + searching.linearSearch(searchList, 9));
List<Integer> sortedList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
System.out.println("Binary search for 5: " + searching.binarySearch(sortedList, 5));
int[] maxMin = searching.findMaxMin(searchList);
System.out.println("Max/Min: " + maxMin[0] + "/" + maxMin[1]);
System.out.println("Duplicates: " + searching.findDuplicates(Arrays.asList(1, 2, 2, 3, 3, 3)));
System.out.println("Count of 3: " + searching.countOccurrences(Arrays.asList(1, 3, 3, 2, 3), 3));
// 4. Sorting
System.out.println("\n--- 4. Array Sorting ---");
ArraySorting sorting = new ArraySorting();
List<Integer> unsorted = new ArrayList<>(Arrays.asList(5, 2, 8, 1, 9, 3));
System.out.println("Original: " + unsorted);
sorting.sortAscending(unsorted);
System.out.println("Sorted ascending: " + unsorted);
List<Integer> sortDescending = new ArrayList<>(Arrays.asList(5, 2, 8, 1, 9, 3));
sorting.sortDescending(sortDescending);
System.out.println("Sorted descending: " + sortDescending);
// 5. Transformations
System.out.println("\n--- 5. Array Transformations ---");
ArrayTransformations transformations = new ArrayTransformations();
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
System.out.println("Filter even: " + transformations.filterEven(numbers));
System.out.println("Filter > 5: " + transformations.filterGreaterThan(numbers, 5));
System.out.println("Double elements: " + transformations.doubleElements(numbers));
System.out.println("Sum: " + transformations.sum(numbers));
System.out.println("Partition even/odd: " + transformations.partitionEvenOdd(numbers));
System.out.println("Chunk by 3: " + transformations.chunkList(numbers, 3));
System.out.println("\n=== All Array Operations Examples Completed ===");
}
}
💻 Operações de Tabela Hash java
🟢 simple
⭐⭐⭐
Usar HashMap e HashSet para armazenamento eficiente de chave-valor e operações de conjunto
⏱️ 30 min
🏷️ java, android, data structures, hash tables
Prerequisites:
Basic Java knowledge, Collections framework
// Android Java Hash Table Operations Examples
// Using HashMap, HashSet, and LinkedHashMap
import java.util.*;
import java.util.stream.Collectors;
// 1. HashMap Basic Operations
public class HashMapOperations {
// Create and initialize HashMap
public void createHashMap() {
// Using HashMap
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("Apple", 10);
hashMap.put("Banana", 20);
hashMap.put("Orange", 30);
hashMap.put("Grape", 40);
System.out.println("HashMap: " + hashMap);
// Using LinkedHashMap (preserves insertion order)
Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("Apple", 10);
linkedHashMap.put("Banana", 20);
linkedHashMap.put("Orange", 30);
System.out.println("LinkedHashMap: " + linkedHashMap);
// Using TreeMap (sorted by keys)
Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("Apple", 10);
treeMap.put("Banana", 20);
treeMap.put("Orange", 30);
System.out.println("TreeMap: " + treeMap);
// Initialize from another map
Map<String, Integer> copyMap = new HashMap<>(hashMap);
System.out.println("Copied map: " + copyMap);
}
// Access elements
public void accessElements(Map<String, Integer> map) {
System.out.println("Value for 'Apple': " + map.get("Apple"));
System.out.println("Value for 'Pear' (default): " + map.getOrDefault("Pear", 0));
// Check if key exists
System.out.println("Contains key 'Apple': " + map.containsKey("Apple"));
System.out.println("Contains value 20: " + map.containsValue(20));
}
// Modify elements
public void modifyElements(Map<String, Integer> map) {
System.out.println("Before: " + map);
// Update existing key
map.put("Apple", 15);
// Put if absent
map.putIfAbsent("Pear", 25);
// Replace if exists
map.replace("Banana", 22);
// Replace with old value check
map.replace("Orange", 30, 35);
// Compute if absent
map.computeIfAbsent("Mango", k -> 50);
// Compute if present
map.computeIfPresent("Grape", (k, v) -> v + 5);
// Merge
map.merge("Apple", 10, Integer::sum);
System.out.println("After: " + map);
}
// Remove elements
public void removeElements(Map<String, Integer> map) {
System.out.println("Before: " + map);
// Remove by key
map.remove("Apple");
// Remove by key and value
map.remove("Banana", 20);
// Clear all
map.clear();
System.out.println("After: " + map);
}
// Iterate over map
public void iterateMap(Map<String, Integer> map) {
System.out.println("Iterate keys:");
for (String key : map.keySet()) {
System.out.println(" Key: " + key);
}
System.out.println("Iterate values:");
for (Integer value : map.values()) {
System.out.println(" Value: " + value);
}
System.out.println("Iterate entries:");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(" " + entry.getKey() + " = " + entry.getValue());
}
// Using forEach (Java 8+)
System.out.println("Using forEach:");
map.forEach((k, v) -> System.out.println(" " + k + " -> " + v));
}
// Get size
public void getSize(Map<String, Integer> map) {
System.out.println("Size: " + map.size());
System.out.println("Is empty: " + map.isEmpty());
}
}
// 2. HashSet Operations
public class HashSetOperations {
// Create and initialize HashSet
public void createHashSet() {
// Using HashSet
Set<Integer> hashSet = new HashSet<>();
hashSet.add(1);
hashSet.add(2);
hashSet.add(3);
hashSet.add(4);
hashSet.add(5);
System.out.println("HashSet: " + hashSet);
// Using LinkedHashSet (preserves insertion order)
Set<Integer> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add(1);
linkedHashSet.add(2);
linkedHashSet.add(3);
System.out.println("LinkedHashSet: " + linkedHashSet);
// Using TreeSet (sorted)
Set<Integer> treeSet = new TreeSet<>();
treeSet.add(5);
treeSet.add(2);
treeSet.add(8);
treeSet.add(1);
System.out.println("TreeSet: " + treeSet);
// Initialize from collection
Set<Integer> fromList = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
System.out.println("From list: " + fromList);
}
// Basic operations
public void basicOperations(Set<Integer> set) {
System.out.println("Original: " + set);
// Add elements
set.add(6);
set.addAll(Arrays.asList(7, 8, 9));
System.out.println("After adding: " + set);
// Check existence
System.out.println("Contains 5: " + set.contains(5));
System.out.println("Contains 10: " + set.contains(10));
// Remove elements
set.remove(5);
set.removeAll(Arrays.asList(2, 4));
System.out.println("After removal: " + set);
}
// Set operations
public void setOperations() {
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
Set<Integer> set2 = new HashSet<>(Arrays.asList(4, 5, 6, 7, 8));
// Union
Set<Integer> union = new HashSet<>(set1);
union.addAll(set2);
System.out.println("Union: " + union);
// Intersection
Set<Integer> intersection = new HashSet<>(set1);
intersection.retainAll(set2);
System.out.println("Intersection: " + intersection);
// Difference
Set<Integer> difference = new HashSet<>(set1);
difference.removeAll(set2);
System.out.println("Difference (set1 - set2): " + difference);
// Check subset
Set<Integer> subset = new HashSet<>(Arrays.asList(1, 2));
System.out.println("Is subset: " + set1.containsAll(subset));
}
// Iterate
public void iterateSet(Set<Integer> set) {
System.out.println("Iterate using for-each:");
for (Integer item : set) {
System.out.println(" " + item);
}
System.out.println("Using forEach:");
set.forEach(item -> System.out.println(" " + item));
System.out.println("Using iterator:");
Iterator<Integer> iterator = set.iterator();
while (iterator.hasNext()) {
System.out.println(" " + iterator.next());
}
}
}
// 3. Advanced Map Operations
public class AdvancedMapOperations {
// Sort map by values
public Map<String, Integer> sortByValue(Map<String, Integer> map) {
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
list.sort(new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Map<String, Integer> result = new LinkedHashMap<>();
for (Map.Entry<String, Integer> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
// Filter map by keys
public Map<String, Integer> filterByKeys(Map<String, Integer> map, Set<String> keys) {
Map<String, Integer> result = new HashMap<>();
for (String key : keys) {
if (map.containsKey(key)) {
result.put(key, map.get(key));
}
}
return result;
}
// Filter map by values
public Map<String, Integer> filterByValues(Map<String, Integer> map, int threshold) {
Map<String, Integer> result = new HashMap<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() > threshold) {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
}
// Invert map (swap keys and values)
public <K, V> Map<V, K> invertMap(Map<K, V> map) {
Map<V, K> inverted = new HashMap<>();
for (Map.Entry<K, V> entry : map.entrySet()) {
inverted.put(entry.getValue(), entry.getKey());
}
return inverted;
}
// Group list items by key
public <T> Map<String, List<T>> groupBy(List<T> items, java.util.function.Function<T, String> keyExtractor) {
Map<String, List<T>> result = new HashMap<>();
for (T item : items) {
String key = keyExtractor.apply(item);
if (!result.containsKey(key)) {
result.put(key, new ArrayList<>());
}
result.get(key).add(item);
}
return result;
}
// Map transformations
public <K, V1, V2> Map<K, V2> mapValues(Map<K, V1> map, java.util.function.Function<V1, V2> mapper) {
Map<K, V2> result = new HashMap<>();
for (Map.Entry<K, V1> entry : map.entrySet()) {
result.put(entry.getKey(), mapper.apply(entry.getValue()));
}
return result;
}
}
// 4. Cache Implementation
public class SimpleCache<K, V> {
private Map<K, V> cache;
private int maxSize;
public SimpleCache(int maxSize) {
this.maxSize = maxSize;
this.cache = new LinkedHashMap<K, V>(maxSize, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > SimpleCache.this.maxSize;
}
};
}
public void put(K key, V value) {
cache.put(key, value);
}
public V get(K key) {
return cache.get(key);
}
public boolean containsKey(K key) {
return cache.containsKey(key);
}
public void remove(K key) {
cache.remove(key);
}
public void clear() {
cache.clear();
}
public int size() {
return cache.size();
}
public Set<K> keySet() {
return cache.keySet();
}
}
// 5. Multi-map (one key, multiple values)
public class Multimap<K, V> {
private Map<K, List<V>> map = new HashMap<>();
public void put(K key, V value) {
if (!map.containsKey(key)) {
map.put(key, new ArrayList<>());
}
map.get(key).add(value);
}
public List<V> get(K key) {
return map.getOrDefault(key, new ArrayList<>());
}
public Set<K> keySet() {
return map.keySet();
}
public boolean containsKey(K key) {
return map.containsKey(key);
}
public int size() {
return map.size();
}
public void remove(K key) {
map.remove(key);
}
public void clear() {
map.clear();
}
}
// Main demonstration
public class HashTableDemo {
public static void demonstrateHashTableOperations() {
System.out.println("=== Android Java Hash Table Operations Examples ===\n");
// 1. HashMap operations
System.out.println("--- 1. HashMap Operations ---");
HashMapOperations hashMapOps = new HashMapOperations();
hashMapOps.createHashMap();
Map<String, Integer> sampleMap = new HashMap<>();
sampleMap.put("Apple", 10);
sampleMap.put("Banana", 20);
sampleMap.put("Orange", 30);
sampleMap.put("Grape", 40);
hashMapOps.accessElements(sampleMap);
hashMapOps.modifyElements(sampleMap);
hashMapOps.iterateMap(sampleMap);
hashMapOps.getSize(sampleMap);
// 2. HashSet operations
System.out.println("\n--- 2. HashSet Operations ---");
HashSetOperations hashSetOps = new HashSetOperations();
hashSetOps.createHashSet();
hashSetOps.setOperations();
Set<Integer> sampleSet = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
hashSetOps.iterateSet(sampleSet);
// 3. Advanced map operations
System.out.println("\n--- 3. Advanced Map Operations ---");
AdvancedMapOperations advancedOps = new AdvancedMapOperations();
Map<String, Integer> unsortedMap = new HashMap<>();
unsortedMap.put("Apple", 40);
unsortedMap.put("Banana", 10);
unsortedMap.put("Orange", 30);
unsortedMap.put("Grape", 20);
Map<String, Integer> sortedByValue = advancedOps.sortByValue(unsortedMap);
System.out.println("Sorted by value: " + sortedByValue);
Map<String, Integer> filtered = advancedOps.filterByValues(unsortedMap, 15);
System.out.println("Filtered (> 15): " + filtered);
// 4. Cache example
System.out.println("\n--- 4. Simple Cache ---");
SimpleCache<String, String> cache = new SimpleCache<>(3);
cache.put("key1", "value1");
cache.put("key2", "value2");
cache.put("key3", "value3");
System.out.println("Cache size: " + cache.size());
System.out.println("Get key1: " + cache.get("key1"));
cache.put("key4", "value4"); // This should evict key1 (LRU)
System.out.println("After adding key4, size: " + cache.size());
System.out.println("Contains key1: " + cache.containsKey("key1"));
// 5. Multimap example
System.out.println("\n--- 5. Multimap ---");
Multimap<String, Integer> multimap = new Multimap<>();
multimap.put("fruits", 1);
multimap.put("fruits", 2);
multimap.put("fruits", 3);
multimap.put("vegetables", 10);
multimap.put("vegetables", 20);
System.out.println("Fruits: " + multimap.get("fruits"));
System.out.println("Vegetables: " + multimap.get("vegetables"));
System.out.println("\n=== All Hash Table Operations Examples Completed ===");
}
}
💻 Operações de Lista Ligada java
🟡 intermediate
⭐⭐⭐⭐
Implementar e manipular listas ligadas simples e duplas com operações comuns
⏱️ 40 min
🏷️ java, android, data structures, linked list
Prerequisites:
Intermediate Java, Understanding of pointers/references
// Android Java Linked List Operations Examples
// Using LinkedList and custom implementations
import java.util.*;
// 1. Java LinkedList Operations
public class JavaLinkedListOperations {
public void demonstrateLinkedList() {
// Create LinkedList
LinkedList<String> list = new LinkedList<>();
// Add elements
list.add("Apple");
list.add("Banana");
list.addFirst("First");
list.addLast("Last");
list.add(2, "Middle");
System.out.println("After adding: " + list);
// Access elements
System.out.println("First: " + list.getFirst());
System.out.println("Last: " + list.getLast());
System.out.println("Element at index 2: " + list.get(2));
// Remove elements
list.removeFirst();
list.removeLast();
list.remove("Middle");
System.out.println("After removal: " + list);
// Using as stack
LinkedList<Integer> stack = new LinkedList<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Stack: " + stack);
System.out.println("Pop: " + stack.pop());
System.out.println("Peek: " + stack.peek());
// Using as queue
LinkedList<Integer> queue = new LinkedList<>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
System.out.println("Queue: " + queue);
System.out.println("Poll: " + queue.poll());
System.out.println("Peek: " + queue.peek());
}
}
// 2. Singly Linked List Implementation
public class SinglyLinkedList<T> {
private Node<T> head;
private int size;
private static class Node<T> {
T data;
Node<T> next;
Node(T data) {
this.data = data;
this.next = null;
}
}
// Add at end
public void add(T data) {
Node<T> newNode = new Node<>(data);
if (head == null) {
head = newNode;
} else {
Node<T> current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
size++;
}
// Add at beginning
public void addFirst(T data) {
Node<T> newNode = new Node<>(data);
newNode.next = head;
head = newNode;
size++;
}
// Add at index
public void add(int index, T data) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException();
}
if (index == 0) {
addFirst(data);
} else if (index == size) {
add(data);
} else {
Node<T> newNode = new Node<>(data);
Node<T> current = head;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
newNode.next = current.next;
current.next = newNode;
size++;
}
}
// Remove first
public T removeFirst() {
if (head == null) {
throw new NoSuchElementException();
}
T data = head.data;
head = head.next;
size--;
return data;
}
// Remove last
public T removeLast() {
if (head == null) {
throw new NoSuchElementException();
}
if (head.next == null) {
T data = head.data;
head = null;
size--;
return data;
}
Node<T> current = head;
while (current.next.next != null) {
current = current.next;
}
T data = current.next.data;
current.next = null;
size--;
return data;
}
// Remove at index
public T remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
if (index == 0) {
return removeFirst();
}
Node<T> current = head;
for (int i = 0; i <index - 1; i++) {
current = current.next;
}
T data = current.next.data;
current.next = current.next.next;
size--;
return data;
}
// Get first
public T getFirst() {
if (head == null) {
throw new NoSuchElementException();
}
return head.data;
}
// Get last
public T getLast() {
if (head == null) {
throw new NoSuchElementException();
}
Node<T> current = head;
while (current.next != null) {
current = current.next;
}
return current.data;
}
// Get at index
public T get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
Node<T> current = head;
for (int i = 0; i < index; i++) {
current = current.next;
}
return current.data;
}
// Size
public int size() {
return size;
}
// Is empty
public boolean isEmpty() {
return head == null;
}
// Clear
public void clear() {
head = null;
size = 0;
}
// To array
public Object[] toArray() {
Object[] array = new Object[size];
Node<T> current = head;
for (int i = 0; i < size; i++) {
array[i] = current.data;
current = current.next;
}
return array;
}
// Reverse
public void reverse() {
Node<T> prev = null;
Node<T> current = head;
Node<T> next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
}
// Contains
public boolean contains(T data) {
Node<T> current = head;
while (current != null) {
if (Objects.equals(current.data, data)) {
return true;
}
current = current.next;
}
return false;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
Node<T> current = head;
while (current != null) {
sb.append(current.data);
if (current.next != null) {
sb.append(" -> ");
}
current = current.next;
}
sb.append("]");
return sb.toString();
}
}
// 3. Doubly Linked List Implementation
public class DoublyLinkedList<T> {
private Node<T> head;
private Node<T> tail;
private int size;
private static class Node<T> {
T data;
Node<T> prev;
Node<T> next;
Node(T data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
// Add at end
public void add(T data) {
Node<T> newNode = new Node<>(data);
if (tail == null) {
head = tail = newNode;
} else {
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
}
size++;
}
// Add at beginning
public void addFirst(T data) {
Node<T> newNode = new Node<>(data);
if (head == null) {
head = tail = newNode;
} else {
newNode.next = head;
head.prev = newNode;
head = newNode;
}
size++;
}
// Remove first
public T removeFirst() {
if (head == null) {
throw new NoSuchElementException();
}
T data = head.data;
head = head.next;
if (head != null) {
head.prev = null;
} else {
tail = null;
}
size--;
return data;
}
// Remove last
public T removeLast() {
if (tail == null) {
throw new NoSuchElementException();
}
T data = tail.data;
tail = tail.prev;
if (tail != null) {
tail.next = null;
} else {
head = null;
}
size--;
return data;
}
// Get first
public T getFirst() {
if (head == null) {
throw new NoSuchElementException();
}
return head.data;
}
// Get last
public T getLast() {
if (tail == null) {
throw new NoSuchElementException();
}
return tail.data;
}
// Size
public int size() {
return size;
}
// Is empty
public boolean isEmpty() {
return head == null;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
Node<T> current = head;
while (current != null) {
sb.append(current.data);
if (current.next != null) {
sb.append(" <-> ");
}
current = current.next;
}
sb.append("]");
return sb.toString();
}
// Iterate forward
public void iterateForward() {
System.out.print("Forward: ");
Node<T> current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
// Iterate backward
public void iterateBackward() {
System.out.print("Backward: ");
Node<T> current = tail;
while (current != null) {
System.out.print(current.data + " ");
current = current.prev;
}
System.out.println();
}
}
// 4. Linked List Algorithms
public class LinkedListAlgorithms {
// Detect cycle (Floyd's cycle detection)
public static <T> boolean hasCycle(SinglyLinkedList<T> list) {
// This would require exposing the internal nodes
// For demonstration, showing algorithm concept
return false;
}
// Find middle element
public static <T> T findMiddle(LinkedList<T> list) {
if (list.isEmpty()) {
throw new NoSuchElementException();
}
ListIterator<T> slow = list.listIterator();
ListIterator<T> fast = list.listIterator();
while (fast.hasNext() && slow.hasNext()) {
fast.next();
if (fast.hasNext()) {
fast.next();
slow.next();
} else {
break;
}
}
return slow.next();
}
// Check if palindrome
public static boolean isPalindrome(LinkedList<Character> list) {
if (list.size() <= 1) {
return true;
}
// Compare first and last, moving inward
int left = 0;
int right = list.size() - 1;
while (left < right) {
if (!list.get(left).equals(list.get(right))) {
return false;
}
left++;
right--;
}
return true;
}
// Remove duplicates from sorted list
public static <T extends Comparable<T>> void removeDuplicates(LinkedList<T> list) {
if (list.size() <= 1) {
return;
}
Collections.sort(list);
Iterator<T> iterator = list.iterator();
T prev = iterator.next();
while (iterator.hasNext()) {
T current = iterator.next();
if (current.compareTo(prev) == 0) {
iterator.remove();
} else {
prev = current;
}
}
}
}
// Main demonstration
public class LinkedListDemo {
public static void demonstrateLinkedListOperations() {
System.out.println("=== Android Java Linked List Operations Examples ===\n");
// 1. Java LinkedList
System.out.println("--- 1. Java LinkedList ---");
JavaLinkedListOperations javaListOps = new JavaLinkedListOperations();
javaListOps.demonstrateLinkedList();
// 2. Singly Linked List
System.out.println("\n--- 2. Singly Linked List ---");
SinglyLinkedList<Integer> singlyList = new SinglyLinkedList<>();
singlyList.add(1);
singlyList.add(2);
singlyList.add(3);
singlyList.addFirst(0);
singlyList.add(2, 99);
System.out.println("Singly linked list: " + singlyList);
System.out.println("First: " + singlyList.getFirst());
System.out.println("Last: " + singlyList.getLast());
System.out.println("Get(2): " + singlyList.get(2));
System.out.println("Contains 99: " + singlyList.contains(99));
System.out.println("Size: " + singlyList.size());
singlyList.reverse();
System.out.println("After reverse: " + singlyList);
singlyList.removeFirst();
singlyList.removeLast();
System.out.println("After removing first and last: " + singlyList);
// 3. Doubly Linked List
System.out.println("\n--- 3. Doubly Linked List ---");
DoublyLinkedList<String> doublyList = new DoublyLinkedList<>();
doublyList.add("A");
doublyList.add("B");
doublyList.add("C");
doublyList.addFirst("Start");
doublyList.addLast("End");
System.out.println("Doubly linked list: " + doublyList);
doublyList.iterateForward();
doublyList.iterateBackward();
System.out.println("Remove first: " + doublyList.removeFirst());
System.out.println("Remove last: " + doublyList.removeLast());
System.out.println("After removals: " + doublyList);
// 4. Algorithms
System.out.println("\n--- 4. Linked List Algorithms ---");
LinkedList<Integer> numberList = new LinkedList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
System.out.println("Find middle of " + numberList + ": " + LinkedListAlgorithms.findMiddle(numberList));
LinkedList<Character> charList = new LinkedList<>(Arrays.asList('r', 'a', 'c', 'e', 'c', 'a', 'r'));
System.out.println("Is palindrome " + charList + ": " + LinkedListAlgorithms.isPalindrome(charList));
LinkedList<Character> notPalindrome = new LinkedList<>(Arrays.asList('h', 'e', 'l', 'l', 'o'));
System.out.println("Is palindrome " + notPalindrome + ": " + LinkedListAlgorithms.isPalindrome(notPalindrome));
LinkedList<Integer> withDuplicates = new LinkedList<>(Arrays.asList(1, 2, 2, 3, 3, 4, 5));
System.out.println("Before removing duplicates: " + withDuplicates);
LinkedListAlgorithms.removeDuplicates(withDuplicates);
System.out.println("After removing duplicates: " + withDuplicates);
System.out.println("\n=== All Linked List Operations Examples Completed ===");
}
}