我有一个字符串,我正在转换为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()));
最好的解决方法是什么,以便我可以按照&#34的方式打印;我的家包括1间起居室,3间卧室,2间浴室和1间家庭活动室。&#34 ;
目前,我的解决方案如下。我还没有接受答案,因为我认为我所遵循的方式有点笨重:
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();
}
答案 0 :(得分:1)
我建议您获取所有元素的频率并提取您需要的内容,而不是一次又一次地扫描该集合。
Map<String, Long> count = Stream.of(myString.split(","))
.collect(Collectors.groupingBy(w -> w, Collectors.counting());