Tech Jargon - Decoded
前往频道在 Telegram
Confused by tech terms? Don’t worry, we’ve got you 🤝 We make things simple, one concept at a time. Learn daily Easy & clear Turn Confusion into clarity. #tech #it #softwareengineer #cs #development
显示更多2 017
订阅者
无数据24 小时
-77 天
-4030 天
帖子存档
Reverse an ArrayList
import java.util.ArrayList;
import java.util.Collections;
public class ReverseArrayList {
public static void main(String[] args) {
ArrayList<String> myList = new ArrayList<>();
myList.add("Apple");
myList.add("Banana");
myList.add("Cherry");
System.out.println("Original List: " + myList);
Collections.reverse(myList);
System.out.println("Reversed List: " + myList);
}
}TreeMap for Sorted Key-Value Pairs
import java.util.TreeMap;
import java.util.Map;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap<String, Integer> treeMap = new TreeMap<>();
treeMap.put("Charlie", 3);
treeMap.put("Alice", 1);
treeMap.put("Bob", 2);
System.out.println("TreeMap: " + treeMap);
for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}HashMap Iteration using entrySet and keySet
import java.util.HashMap;
import java.util.Map;
public class HashMapIteration {
public static void main(String[] args) {
HashMap<String, Integer> studentGrades = new HashMap<>();
studentGrades.put("Alice", 95);
studentGrades.put("Bob", 80);
studentGrades.put("Charlie", 75);
System.out.println("Iterating using entrySet:");
for (Map.Entry<String, Integer> entry : studentGrades.entrySet()) {
System.out.println("Name: " + entry.getKey() + ", Grade: " + entry.getValue());
}
System.out.println("
Iterating using keySet:");
for (String key : studentGrades.keySet()) {
System.out.println("Name: " + key + ", Grade: " + studentGrades.get(key));
}
}
}Sorting Custom Objects with Comparator
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Student {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" + "name='" + name + '\'' + ", age=" + age + '}';
}
}
class SortByAge implements Comparator<Student> {
public int compare(Student a, Student b) {
return a.age - b.age;
}
}
public class SortStudents {
public static void main(String[] args) {
ArrayList<Student> studentList = new ArrayList<>();
studentList.add(new Student("Alice", 20));
studentList.add(new Student("Bob", 18));
studentList.add(new Student("Charlie", 22));
System.out.println("Before sorting: " + studentList);
Collections.sort(studentList, new SortByAge());
System.out.println("After sorting by age: " + studentList);
}
}Sort ArrayList using Collections.sort()
import java.util.ArrayList;
import java.util.Collections;
public class SortArrayList {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Banana");
list.add("Apple");
list.add("Orange");
list.add("Grapes");
System.out.println("Before sorting: " + list);
Collections.sort(list);
System.out.println("After sorting: " + list);
}
}Element Frequency Counter with HashMap
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FrequencyCounter {
public static void main(String[] args) {
List<String> elements = new ArrayList<>();
elements.add("apple");
elements.add("banana");
elements.add("apple");
elements.add("orange");
elements.add("banana");
elements.add("apple");
Map<String, Integer> frequencyMap = calculateFrequency(elements);
for (Map.Entry<String, Integer> entry : frequencyMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
public static Map<String, Integer> calculateFrequency(List<String> list) {
Map<String, Integer> frequencyMap = new HashMap<>();
for (String element : list) {
frequencyMap.put(element, frequencyMap.getOrDefault(element, 0) + 1);
}
return frequencyMap;
}
}Remove Duplicates from ArrayList using HashSet
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RemoveDuplicates {
public static void main(String[] args) {
ArrayList<String> listWithDuplicates = new ArrayList<>();
listWithDuplicates.add("Apple");
listWithDuplicates.add("Banana");
listWithDuplicates.add("Apple");
listWithDuplicates.add("Orange");
listWithDuplicates.add("Banana");
ArrayList<String> listWithoutDuplicates = removeDuplicates(listWithDuplicates);
System.out.println("List with duplicates: " + listWithDuplicates);
System.out.println("List without duplicates: " + listWithoutDuplicates);
}
public static ArrayList<String> removeDuplicates(ArrayList<String> listWithDuplicates) {
Set<String> set = new HashSet<>(listWithDuplicates);
return new ArrayList<>(set);
}
}ArrayList Example
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println("Original list: " + names);
Collections.sort(names);
System.out.println("Sorted list: " + names);
names.remove("Bob");
System.out.println("List after removing Bob: " + names);
System.out.println("Size of the list: " + names.size());
}
}and improves code readability.
- Choose the right data structure for the job. If you need to store key-value pairs, use a `HashMap`. If you need a dynamic list, use an `ArrayList`. 💡
- Be aware of the performance characteristics of each data structure. For example, accessing an element in an `ArrayList` by index is very fast, but searching for an element can be slower. ⚠️
By mastering `ArrayList`, `HashMap`, and `Collections`, you'll be well on your way to writing more efficient and powerful Java programs! 🚀
Let's explore the wonderful world of `ArrayList`, `HashMap`, and `Collections` in Java! These are your secret weapons for writing efficient and powerful code. Think of them as pre-built tools that save you time and effort. 🛠️
**1. ArrayList: Your Flexible List 📝**
Imagine you need to store a list of your favorite songs. You could use a regular array, but arrays have a fixed size. What if you want to add more songs later? That's where `ArrayList` comes to the rescue!
- `ArrayList` is a dynamic array, meaning it can grow or shrink in size as needed. It's part of the `java.util` package, so you'll need to import it: `import java.util.ArrayList;`
- Creating an `ArrayList`: `ArrayList mySongs = new ArrayList<>();` This creates an `ArrayList` that can hold `String` objects (your song titles, for example). The `` part is important; it tells Java what type of objects the `ArrayList` will store. This is called using *Generics*. 🧠
- Adding elements: `mySongs.add("Bohemian Rhapsody");` Now your list has one song! You can add more songs using `add()`.
- Accessing elements: `String firstSong = mySongs.get(0);` This gets the song at index 0 (the first song). Remember, indexing starts at 0!
- Other useful methods:
- `size()` -> Returns the number of elements in the list.
- `remove(index)` -> Removes the element at the specified index.
- `contains(element)` -> Checks if the list contains a specific element.
- `clear()` -> Removes all elements from the list.
**2. HashMap: Your Key-Value Storage 🗝️**
Think of a dictionary. You look up a word (the key) to find its definition (the value). `HashMap` works the same way. It stores data in key-value pairs.
- `HashMap` is also part of the `java.util` package: `import java.util.HashMap;`
- Creating a `HashMap`: `HashMap songLengths = new HashMap<>();` This creates a `HashMap` that maps `String` keys (song titles) to `Integer` values (song lengths in seconds).
- Adding key-value pairs: `songLengths.put("Bohemian Rhapsody", 355);` Now you know Bohemian Rhapsody is 355 seconds long.
- Accessing values: `int length = songLengths.get("Bohemian Rhapsody");` This retrieves the length of the song.
- Important notes:
- Keys must be unique. If you try to add the same key again with a different value, the old value will be overwritten.
- `HashMap` doesn't guarantee any specific order of elements.
**3. Collections: Your Utility Belt for Lists and More 🧰**
The `Collections` class provides a set of static methods for working with collections (like `ArrayList` and `HashMap`). Think of it as a utility belt full of helpful tools!
- Some useful methods:
- `Collections.sort(mySongs);` -> Sorts the elements in an `ArrayList` in ascending order.
- `Collections.shuffle(mySongs);` -> Randomly shuffles the elements in an `ArrayList`.
- `Collections.max(myNumbers);` -> Returns the maximum value in a collection.
- `Collections.min(myNumbers);` -> Returns the minimum value in a collection.
**Why use these? 🤔**
- **Faster development:** These structures are already built, tested, and optimized. You don't have to write your own data structures from scratch. ✅
- **Efficiency:** They're designed to perform common operations (like adding, removing, and searching) efficiently. ✅
- **Readability:** Using these standard structures makes your code easier to understand for other developers. ✅
**Example scenario:**
Let's say you're building a music player app. You could use an `ArrayList` to store the list of songs, a `HashMap` to store song titles and their corresponding file paths, and `Collections.shuffle()` to create a random playlist. 🎶
**Best Practices:**
- Always specify the data type using Generics (e.g., `ArrayList`). This helps prevent errors
Remove Duplicate Characters from a String
public class RemoveDuplicates {
public static String removeDuplicates(String str) {
String result = "";
for (int i = 0; i < str.length(); i++) {
char currentChar = str.charAt(i);
if (result.indexOf(currentChar) < 0) {
result += currentChar;
}
}
return result;
}
public static void main(String[] args) {
String input = "programming";
String output = removeDuplicates(input);
System.out.println(output);
}
}Count Word Occurrences in a String
public class WordCounter {
public static void main(String[] args) {
String text = "This is a string this is a test";
String[] words = text.split(" ");
java.util.HashMap<String, Integer> wordCounts = new java.util.HashMap<>();
for (String word : words) {
if (wordCounts.containsKey(word)) {
wordCounts.put(word, wordCounts.get(word) + 1);
} else {
wordCounts.put(word, 1);
}
}
for (java.util.Map.Entry<String, Integer> entry : wordCounts.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}Check if Strings are Rotations
public class StringRotation {
public static boolean areRotations(String str1, String str2) {
if (str1.length() != str2.length()) {
return false;
}
String temp = str1 + str1;
return temp.contains(str2);
}
public static void main(String[] args) {
String str1 = "ABCD";
String str2 = "CDAB";
if (areRotations(str1, str2)) {
System.out.println("Strings are rotations of each other");
} else {
System.out.println("Strings are not rotations of each other");
}
}
}First Non-Repeating Character in a String
public class FirstNonRepeating {
public static char findFirstNonRepeating(String str) {
if (str == null || str.isEmpty()) {
return '\0';
}
for (int i = 0; i < str.length(); i++) {
boolean repeating = false;
for (int j = 0; j < str.length(); j++) {
if (i != j && str.charAt(i) == str.charAt(j)) {
repeating = true;
break;
}
}
if (!repeating) {
return str.charAt(i);
}
}
return '\0';
}
public static void main(String[] args) {
String input = "leetcode";
char result = findFirstNonRepeating(input);
System.out.println("First non-repeating character: " + result);
}
}String Contains Only Digits
public class StringDigits {
public static boolean isOnlyDigits(String str) {
if (str == null || str.isEmpty()) {
return false;
}
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String testString1 = "12345";
String testString2 = "123abc";
System.out.println(testString1 + " is only digits: " + isOnlyDigits(testString1));
System.out.println(testString2 + " is only digits: " + isOnlyDigits(testString2));
}
}Replace a character in a string
public class ReplaceChar {
public static void main(String[] args) {
String str = "Hello World";
char oldChar = 'o';
char newChar = 'a';
String newStr = str.replace(oldChar, newChar);
System.out.println(newStr);
}
}Remove Vowels from a String
public class RemoveVowels {
public static String removeVowels(String str) {
String vowels = "AEIOUaeiou";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (vowels.indexOf(c) == -1) {
sb.append(c);
}
}
return sb.toString();
}
public static void main(String[] args) {
String input = "Hello World";
String result = removeVowels(input);
System.out.println(result);
}
}String to Uppercase and Lowercase (No Built-in Methods)
public class StringConverter {
public static String toUpperCase(String str) {
char[] charArray = str.toCharArray();
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] >= 'a' && charArray[i] <= 'z') {
charArray[i] = (char)(charArray[i] - 32);
}
}
return new String(charArray);
}
public static String toLowerCase(String str) {
char[] charArray = str.toCharArray();
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] >= 'A' && charArray[i] <= 'Z') {
charArray[i] = (char)(charArray[i] + 32);
}
}
return new String(charArray);
}
public static void main(String[] args) {
String input = "Hello World";
String upper = toUpperCase(input);
String lower = toLowerCase(input);
System.out.println("Original: " + input);
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}Count words in a string
public class WordCounter {
public static void main(String[] args) {
String text = "This is a simple example string";
int wordCount = countWords(text);
System.out.println("Word count: " + wordCount);
}
public static int countWords(String str) {
if (str == null || str.isEmpty()) {
return 0;
}
String[] words = str.split("\\s+");
return words.length;
}
}
现已上线!2025 年 Telegram 研究 — 年度关键洞察 
