Java 在ArrayList()中查找最常见的字符串
有没有办法在Java 在ArrayList()中查找最常见的字符串,java,arrays,list,arraylist,Java,Arrays,List,Arraylist,有没有办法在数组列表中找到最常见的字符串 ArrayList<String> list = new ArrayList<>(); list.add("test"); list.add("test"); list.add("hello"); list.add("test"); ArrayList list=new ArrayList(); 列表。添加(“测试”); 列表。添加(“测试”); 添加(“你好”); 列表。添加(“测试”); 应该从这个列表中找到“test”一
数组列表
中找到最常见的字符串
ArrayList<String> list = new ArrayList<>();
list.add("test");
list.add("test");
list.add("hello");
list.add("test");
ArrayList list=new ArrayList();
列表。添加(“测试”);
列表。添加(“测试”);
添加(“你好”);
列表。添加(“测试”);
应该从这个列表中找到“test”一词
[“test”,“test”,“hello”,“test”]
我认为最好的方法是使用包含计数的映射
Map<String, Integer> stringsCount = new HashMap<>();
最后,您可以获得在地图上迭代次数最多的元素:
Map.Entry<String,Integer> mostRepeated = null;
for(Map.Entry<String, Integer> e: stringsCount.entrySet())
{
if(mostRepeated == null || mostRepeated.getValue()<e.getValue())
mostRepeated = e;
}
您可以制作一个
HashMap
。如果字符串已经出现在映射中,则将其键增加1,否则,将其添加到映射中
例如:
put("someValue", 1);
然后,再次假设它是“someValue”,您可以执行以下操作:
put("someValue", get("someValue") + 1);
因为“someValue”的键是1,现在当你放置它时,键将是2
之后,您可以轻松浏览地图并提取具有最高值的键
我没有写一个完整的解决方案,试着构建一个,如果你有问题,在另一个问题中发布。最佳实践是自己学习。您可以使用
HashMap
。在数组中循环,可以检查每个字符串
,如果它还不是HashMap
的键,则添加它并将值设置为1,如果是,则将其值增加1
然后你有一个
HashMap
,其中包含所有唯一的字符串和一个关联的数字,说明它们在数组中的数量。不要重新发明轮子,使用集合
类的频率
方法:
public static int frequency(Collection<?> c, Object o)
有很多答案建议使用HashMaps。我真的不喜欢它们,因为不管怎样,你必须再次遍历它们。相反,我会对列表进行排序
Collections.sort(list);
然后循环通过它。类似于
String prev = null, mostCommon=null;
int num = 0, max = 0;
for (String str:list) {
if (str.equals(prev)) {
num++;
} else {
if (num>max) {
max = num;
mostCommon = str;
}
num = 1;
prev = str;
}
}
应该这样做。如果有人需要从常用字符串[]数组(使用列表)中查找最流行的字符串:
公共字符串findPopular(字符串[]数组){
列表=数组。asList(数组);
Map stringscont=new HashMap();
用于(字符串:列表)
{
if(string.length()>0){
string=string.toLowerCase();
整数计数=stringscont.get(字符串);
如果(count==null)count=新整数(0);
计数++;
stringscont.put(字符串,计数);
}
}
Map.Entry mostRepeated=null;
对于(Map.Entry e:stringscont.entrySet())
{
如果(mostRepeated==null | | mostRepeated.getValue()。一个普通的Java 8解决方案如下所示:
Stream.of("test","test","hello","test")
.collect(Collectors.groupingBy(s -> s, Collectors.counting()))
.entrySet()
.stream()
.max(Comparator.comparing(Entry::getValue))
.ifPresent(System.out::println);
这将产生:
test=3
是一个支持数据流的库。以下程序:
System.out.println(
Seq.of("test","test","hello","test")
.mode()
);
收益率:
Optional[test]
(免责声明:我为jOOλ后面的公司工作)我知道这需要更多的时间来实现,但您可以使用堆数据结构,方法是根据问题将计数和字符串信息存储在节点中,特别是为了获得单词,而不是次数(即键的值)
您可以使用番石榴的Multiset:
ArrayList<String> names = ...
// count names
HashMultiset<String> namesCounts = HashMultiset.create(names);
Set<Multiset.Entry<String>> namesAndCounts = namesCounts.entrySet();
// find one most common
Multiset.Entry<String> maxNameByCount = Collections.max(namesAndCounts, Comparator.comparing(Multiset.Entry::getCount));
// pick all with the same number of occurrences
List<String> mostCommonNames = new ArrayList<>();
for (Multiset.Entry<String> nameAndCount : namesAndCounts) {
if (nameAndCount.getCount() == maxNameByCount.getCount()) {
mostCommonNames.add(nameAndCount.getElement());
}
}
ArrayList名称=。。。
//数名
HashMultiset namesCounts=HashMultiset.create(名称);
Set namesAndCounts=namesCounts.entrySet();
//找到一个最常见的
Multiset.Entry maxNameByCount=Collections.max(namesAndCounts,Comparator.comparing(Multiset.Entry::getCount));
//拾取出现次数相同的所有对象
List mostCommonNames=new ArrayList();
for(Multiset.Entry nameAndCount:nameandcounts){
如果(nameAndCount.getCount()==maxNameByCount.getCount()){
mostCommonNames.add(nameAndCount.getElement());
}
}
公共类字符串检查器{
public static void main(String[] args) {
ArrayList<String> string;
string = new ArrayList<>(Arrays.asList("Mah", "Bob", "mah", "bat", "MAh", "BOb"));
Map<String, Integer> wordMap = new HashMap<String, Integer>();
for (String st : string) {
String input = st.toUpperCase();
if (wordMap.get(input) != null) {
Integer count = wordMap.get(input) + 1;
wordMap.put(input, count);
} else {
wordMap.put(input, 1);
}
}
System.out.println(wordMap);
Object maxEntry = Collections.max(wordMap.entrySet(), Map.Entry.comparingByValue()).getKey();
System.out.println("maxEntry = " + maxEntry);
publicstaticvoidmain(字符串[]args){
数组列表字符串;
string=newarraylist(Arrays.asList(“Mah”、“Bob”、“Mah”、“bat”、“Mah”、“Bob”));
Map wordMap=newhashmap();
for(字符串st:String){
字符串输入=st.toUpperCase();
if(wordMap.get(输入)!=null){
整数计数=wordMap.get(输入)+1;
put(输入,计数);
}否则{
wordMap.put(输入,1);
}
}
System.out.println(wordMap);
Object maxEntry=Collections.max(wordMap.entrySet(),Map.Entry.comparingByValue()).getKey();
System.out.println(“maxEntry=“+maxEntry”);
}使用此方法,如果ArrayList中有多个最常见的元素,则可以通过将它们添加到新的ArrayList中来获取所有元素
public static void main(String[] args) {
List <String> words = new ArrayList<>() ;
words.add("cat") ;
words.add("dog") ;
words.add("egg") ;
words.add("chair") ;
words.add("chair") ;
words.add("chair") ;
words.add("dog") ;
words.add("dog") ;
Map<String,Integer> count = new HashMap<>() ;
for (String word : words) { /* Counts the quantity of each
element */
if (! count.containsKey(word)) {
count.put(word, 1 ) ;
}
else {
int value = count.get(word) ;
value++ ;
count.put(word, value) ;
}
}
List <String> mostCommons = new ArrayList<>() ; /* Max elements */
for ( Map.Entry<String,Integer> e : count.entrySet() ) {
if (e.getValue() == Collections.max(count.values() )){
/* The max value of count */
mostCommons.add(e.getKey()) ;
}
}
System.out.println(mostCommons);
}
}
publicstaticvoidmain(字符串[]args){
List words=new ArrayList();
词语。添加(“cat”);
字。加上(“狗”);
字。加上(“蛋”);
字。加上(“主席”);
字。加上(“主席”);
字。加上(“主席”);
字。加上(“狗”);
字。加上(“狗”);
映射计数=新的HashMap();
for(String-word:words){/*计算每个字符串的数量
元素*/
如果(!count.containsKey(word)){
数一数(字,1);
}
否则{
int值=count.get(字);
值++;
count.put(字、值);
}
}
列出mostCommons=new ArrayList();/*最大元素*/
对于(Map.Entry e:count.entrySet()){
if(e.getValue()==Collections.max(count.values())){
/*计数的最大值*/
添加(例如getKey());
}
}
System.out.println(大多数常见);
}
}
是的,有一种方法。但没有直接的方法。你必须编写一些代码。是的,你必须使用Map,例如HashMap“我真的不喜欢它们”…对一组值进行两次迭代仍然是O(N)
复杂度。你的算法使用排序,即O(N log N)
复杂性,这当然更糟。我同意Bex。在我看来,排序实际上不是一个坏主意。它易于实现,并且具有O(nlogn)时间复杂性和O(1)空间。而使用hashmap和priorityqueue则具有O(nlogn)时间复杂性和O(n)空间。因为插入pq的是O(logn),迭代Hashmap的条目,并在最坏的情况下将它们插入pq is O(nlogn)。如果我错了,请纠正我。使用Function.identit代替w->w
Optional[test]
String mostRepeatedWord
= list.stream()
.collect(Collectors.groupingBy(w -> w, Collectors.counting()))
.entrySet()
.stream()
.max(Comparator.comparing(Entry::getValue))
.get()
.getKey();
ArrayList<String> names = ...
// count names
HashMultiset<String> namesCounts = HashMultiset.create(names);
Set<Multiset.Entry<String>> namesAndCounts = namesCounts.entrySet();
// find one most common
Multiset.Entry<String> maxNameByCount = Collections.max(namesAndCounts, Comparator.comparing(Multiset.Entry::getCount));
// pick all with the same number of occurrences
List<String> mostCommonNames = new ArrayList<>();
for (Multiset.Entry<String> nameAndCount : namesAndCounts) {
if (nameAndCount.getCount() == maxNameByCount.getCount()) {
mostCommonNames.add(nameAndCount.getElement());
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public static void main(String[] args) {
ArrayList<String> string;
string = new ArrayList<>(Arrays.asList("Mah", "Bob", "mah", "bat", "MAh", "BOb"));
Map<String, Integer> wordMap = new HashMap<String, Integer>();
for (String st : string) {
String input = st.toUpperCase();
if (wordMap.get(input) != null) {
Integer count = wordMap.get(input) + 1;
wordMap.put(input, count);
} else {
wordMap.put(input, 1);
}
}
System.out.println(wordMap);
Object maxEntry = Collections.max(wordMap.entrySet(), Map.Entry.comparingByValue()).getKey();
System.out.println("maxEntry = " + maxEntry);
public static void main(String[] args) {
List <String> words = new ArrayList<>() ;
words.add("cat") ;
words.add("dog") ;
words.add("egg") ;
words.add("chair") ;
words.add("chair") ;
words.add("chair") ;
words.add("dog") ;
words.add("dog") ;
Map<String,Integer> count = new HashMap<>() ;
for (String word : words) { /* Counts the quantity of each
element */
if (! count.containsKey(word)) {
count.put(word, 1 ) ;
}
else {
int value = count.get(word) ;
value++ ;
count.put(word, value) ;
}
}
List <String> mostCommons = new ArrayList<>() ; /* Max elements */
for ( Map.Entry<String,Integer> e : count.entrySet() ) {
if (e.getValue() == Collections.max(count.values() )){
/* The max value of count */
mostCommons.add(e.getKey()) ;
}
}
System.out.println(mostCommons);
}
}