本文介绍了是否有一个像“ Set”这样的对象?只能包含唯一的字符串值,还可以包含对字符串值出现次数的计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,是否有一个像集这样的对象,它只能包含唯一的字符串值,还可以计算字符串值的出现次数?

In Java is there an object like a "Set" that can contain only unique string values, but also contain a count on the number of occurrences of the string value?

这个想法很简单

具有数据集ala ...

With a data set ala...

A
B
B
C
C
C

ABBCCC

我想将每一行文本添加到Set中目的。每次将不唯一的文本添加到集合中时,我都希望也有一个与集合相关联的数字值,以显示添加了多少次。因此,如果我在上述数据集上运行它,输出将类似于:

I'd like to add each line of text to a Set-like object. Each time that a non-unique text is added to the set I'd like to also have a numeric value associated with the set to display how many times it was added. So if I ran it on the above data set the output would be something like:

A:1
B:2
C:3

A : 1B : 2C : 3

有什么想法吗?

推荐答案

Map< String,Integer> 是最好的选择,用文字表达您想要做的是映射字符串的出现次数。基本上是这样的:

Map<String, Integer> would be the best bet, to put in words what you want to do is to Map the amount of occurrences of a string. Basically have something like this:

public void add(String s) {
    if (map.containsKey(s)) {
        map.put(s, map.get(s) + 1);
    } else {
        map.put(s, 1);
    }
}

这篇关于是否有一个像“ Set”这样的对象?只能包含唯一的字符串值,还可以包含对字符串值出现次数的计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 01:07