集合是指包含一组元素的对象,这些元素无序且不重复。在Java中,集合类被封装在java.util包中,其中包括List、Set和Map等常用的集合类型。
创建集合可以使用Java中提供的集合类,例如:
// 创建一个空的ArrayList集合
List<String> list = new ArrayList<>();
// 创建一个HashSet集合,并添加元素
Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(3);
// 创建一个HashMap集合,并添加键值对
Map<String, Integer> map = new HashMap<>();
map.put("Alice", 20);
map.put("Bob", 25);
map.put("Charlie", 30);
可以使用Java中的foreach循环遍历集合中的元素,例如:
// 遍历ArrayList集合
for (String str : list) {
System.out.println(str);
}
// 遍历HashSet集合
for (Integer i : set) {
System.out.println(i);
}
// 遍历HashMap集合
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + ": " + value);
}
一个简单的使用集合的示例是统计一段文本中每个单词出现的次数。可以将所有单词存储在一个List集合中,然后使用一个HashMap来记录每个单词出现的次数。例如:
String text = "This is a sample text for testing purpose. This text contains several words that repeat multiple times. The purpose of this test is to count the frequency of each word.";
List<String> words = Arrays.asList(text.split("\\W+"));
Map<String, Integer> freqMap = new HashMap<>();
for (String word : words) {
String lowercaseWord = word.toLowerCase();
if (freqMap.containsKey(lowercaseWord)) {
freqMap.put(lowercaseWord, freqMap.get(lowercaseWord) + 1);
} else {
freqMap.put(lowercaseWord, 1);
}
}
System.out.println(freqMap);
以上代码将文本分割成单词,然后遍历每个单词并更新它在HashMap中的频率。最后输出每个单词及其出现的次数。
总结:集合是一种存储一组元素的对象,可以使用Java中提供的集合类来创建和操作集合。常见的集合类型包括List、Set和Map等。集合的使用可以简化程序的编写,并提高代码的可读性和效率。