gpt4 book ai didi

java - 用于显示 Java ArrayList 中唯一值出现次数的字符串

转载 作者:行者123 更新时间:2023-11-30 07:36:00 26 4
gpt4 key购买 nike

我有一个字符串,正在将其转换为 ArrayList,目的是计算列表中特定值的数量。

我的字符串可能如下所示:

String myString = "Living Room, Bedroom, Bedroom, Bedroom, Bathroom, Bathroom, Family Room."

我目前正在通过这种方式查找唯一值出现的次数:

Map<String, Long> count = Stream.of(myString.split(",")).collect(Collectors.groupingBy(w -> w, Collectors.counting()));

最好的方法是什么,以便我可以打印类似“我的家包括 1 间客厅、3 间卧室、2 间浴室和 1 间家庭 Activity 室”的内容。

<小时/>

目前,我的解决方案如下。我还没有接受答案,因为我认为我遵循的方式有点笨拙:

String newDescription = "My Home includes ";

public String getDescription(){
String myDescription = home.getDescription();

Map<String, Long> count = Stream.of(myDescription.split(",")).collect(Collectors.groupingBy(w -> w, Collectors.counting()));

for (Map.Entry<String, Long> entry : count.entrySet()){
newDescription = newDescription + entry.getValue() + " " + entry.getKey() + "(s), ";
}
return newDescription;
}
<小时/>

我之前是这样处理的,但另一个 SO 用户建议进行更改:

public ArrayList convertDescription(){
//getDescription is inherited from another class to provide a string like the myString example above
String myDescription = home.getDescription();

ArrayList<String>Map<String, listDescriptionLong> =count new= ArrayList<String>(ArraysStream.asListof(myDescription.split(",")));

int livingRoomOccurrences = Collections.frequencycollect(listDescription, "Living Room");
int bedroomOccurrences = CollectionsCollectors.frequencygroupingBy(listDescription, "Bedroom");
int bathroomOccurrencesw =-> Collections.frequency(listDescriptionw, "Bathroom");
int familyRoomOccurrences = CollectionsCollectors.frequencycounting(listDescription, "Family Room");
int kitchenOccurrences = Collections.frequency(listDescription, "Kitchen");
int walkInClosetOccurrences = Collections.frequency(listDescription, "Walk-in Closet");
//not sure what I should return to make it easy to override getDescription with the proper string formatting
return listDescription;
}

public String getDescription(){
return home.getDescription();
}

最佳答案

我建议你获取所有元素的频率并提取你需要的内容,而不是一遍又一遍地扫描集合。

Map<String, Long> count = Stream.of(myString.split(","))
.collect(Collectors.groupingBy(w -> w, Collectors.counting());

关于java - 用于显示 Java ArrayList 中唯一值出现次数的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35385096/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com