List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
Integer number = iterator.next();
if (number == 2) {
iterator.remove(); // 正确的删除方式,不会抛出ConcurrentModificationException
}
}
class Person implements Comparable<Person> {
private String name;
private int age;
// Constructors, getters, setters
@Override
public int compareTo(Person otherPerson) {
return Integer.compare(this.age, otherPerson.age);
}
}
List<Person> people = new ArrayList<>();
// Add people to the list
Collections.sort(people); // 使用自然排序
// 使用Comparator进行定制排序
Comparator<Person> ageComparator = Comparator.comparingInt(Person::getAge);
Collections.sort(people, ageComparator);
WeakHashMap<Key, Value> weakMap = new WeakHashMap<>();
Key key = new Key(); // 仅被weakMap引用
Value value = new Value(); // 与key相关的值
weakMap.put(key, value);
// 当key不再被其他部分引用,垃圾回收时,weakMap中的对应条目会被移除
class Student {
private int id;
private String name;
// Constructors, getters, setters
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return id == student.id && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}
IdentityHashMap<String, Integer> identityMap = new IdentityHashMap<>();
String key1 = new String("key");
String key2 = new String("key");
identityMap.put(key1, 1);
identityMap.put(key2, 2);
System.out.println(identityMap.size()); // 输出 2,因为两个键在引用上不同
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.parallelStream()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.sum();
ConcurrentSkipListMap<String, Integer> skipListMap = new ConcurrentSkipListMap<>();
skipListMap.put("one", 1);
skipListMap.put("two", 2);
int value = skipListMap.get("two");