search
HomeJavajavaTutorialA piece of code to understand the use of List, Set and Map in Java

The usage codes of List, Set collection and Map in Java are as follows:

package tingjizifu;
import java.util.*;
public class TongJi {
/*
* 使用Scanner从控制台读取一个字符串,统计字符串中每个字符出现的次数,要求使用学习过的知识完成以上要求
* 实现思路根据Set、List、Map集合的特性完成。
*/
public static void main(String[] args) {
// 输入字符串
Scanner input = new Scanner(System.in);
String shuRu = input.next();
// 把字符串字符装入List集合
List<String> list = new ArrayList<String>();
for (int i = 0; i < shuRu.length(); i++) {
list.add(String.valueOf(shuRu.charAt(i)));
}
// 把字符串字符装入Set集合
Set<String> set = new HashSet<String>();
for (int i = 0; i < shuRu.length(); i++) {
set.add(String.valueOf(shuRu.charAt(i)));
}
// 用Set中的字符与List中的字符进行比较,相同就加1进行计数,
// 然后把Set集合中的字符作为键(key),统计的数作为值(value),最后打印出Map中的数据
Map<String, Integer> map = new HashMap<String, Integer>();
for (String str : set) {
int sum = 0;
// System.out.println(str);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(str)) {
sum++;
}
}
map.put(str, sum);
}
Set<String> ss = map.keySet();
for (String str : ss) {
System.out.println(str + "出现次数为" + map.get(str) + "次");
}
input.close();
}
}

Let’s look at the difference between set map list

They are all collection interfaces

set --The values ​​are not allowed to be repeated, an unordered data structure
list --The values ​​are allowed to be repeated, because it is an ordered data structure
map --A paired data structure, the key value must have Uniqueness (the keys cannot be the same, otherwise the value will be replaced)

List saves the objects in the order they are entered, without sorting or editing operations.

Set accepts each object only once and uses its own internal sorting method (usually, you only care about whether an element belongs to the Set, not its order - otherwise you should use List ).

Map also saves a copy of each element, but this is based on "key". Map also has built-in sorting, so it does not care about the order in which elements are added. If the order of adding elements is important to you, you should use LinkedHashSet or LinkedHashMap.

Collection is a collection of objects. Collection has two sub-interfaces List and Set

List can be passed Subscript (1,2..) to get the value, the value can be repeated

, while Set can only get the value through the cursor, and the value cannot be repeated

ArrayList, Vector, and LinkedList are the implementation classes of List

ArrayList is thread-unsafe, and Vector is thread-safe. The underlying layers of these two classes are implemented by arrays

LinkedList is thread-unsafe, and the bottom layer is implemented by a linked list

Map is a collection of key-value pairs

HashTable and HashMap are the implementation classes of Map

HashTable is thread-safe and cannot store null values

HashMap is not thread-safe and can store null values

The above is what the editor introduces to you about Java I hope this knowledge about the use of List, Set and Map will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank you all for your support of the PHP Chinese website!

For more articles about the use of List, Set and Map in Java, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteTop 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteMar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

Node.js 20: Key Performance Boosts and New FeaturesNode.js 20: Key Performance Boosts and New FeaturesMar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedSpring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedMar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

Iceberg: The Future of Data Lake TablesIceberg: The Future of Data Lake TablesMar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

How to Share Data Between Steps in CucumberHow to Share Data Between Steps in CucumberMar 07, 2025 pm 05:55 PM

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

How can I implement functional programming techniques in Java?How can I implement functional programming techniques in Java?Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment