英文:
How do I count the amount of times a specific word comes up in an array list
问题
import java.io.File;
import java.util.ArrayList;
import java.io.IOException;
import java.util.Scanner;
public class Artists {
public static ArrayList<String> artists = new ArrayList<String>();
public static void main(String[] args) {
System.out.println(readArtists("artists30.txt"));
System.out.println(artists + "\n");
}
public Artists() {
}
public static boolean readArtists(String fileName) {
Scanner sc = null;
try {
File file = new File(fileName);
if (file.createNewFile()) {
System.out.println("err " + fileName);
return false;
}
sc = new Scanner(file);
while (sc.hasNextLine()) {
artists.add(sc.nextLine());
}
} catch (Exception e) {
e.printStackTrace();
}
if (sc != null) {
sc.close();
}
return true;
}
public int count() {
int count = artists.size();
return count;
}
public int count(String genre) {
int genreCount = 0;
for (String artistInfo : artists) {
String[] parts = artistInfo.split(" ");
if (parts.length >= 2 && parts[1].equalsIgnoreCase(genre)) {
genreCount++;
}
}
return genreCount;
}
}
英文:
I have a class that takes in a txt file with artists and their genre in the format:
Abba Rock
Beethoven Classical
I am trying to write a method "public int count(String genre)" that counts the amount of times that word/genre is present. For example, for rock, it would need to count the number of rock artists and satisfy my test case:
public class ArtistTest
{
public static void main(String[] args)
{
Artists artists = new Artists();
System.out.println(artists.count() + " artists in the list");
System.out.println(artists.count("Rock") + " rock artists in the list\n");
My initial count method successfully counts the number of artists (I guess there would be a better way to do that)
My code so far:
import java.io.File;
import java.util.ArrayList;
import java.io.IOException;
import java.util.Scanner;
public class Artists {
public static ArrayList<String> artists = new ArrayList<String>();
public static void main(String[] args) {
System.out.println(readArtists("artists30.txt"));
System.out.println(artists + "\n");
}
public Artists() {
}
public static boolean readArtists(String fileName) {
Scanner sc = null;
try {
File file = new File(fileName);
if (file.createNewFile()) {
System.out.println("err " + fileName);
return false;
}
sc = new Scanner(file);
while (sc.hasNextLine()) {
artists.add(sc.nextLine());
}
} catch (Exception e) {
e.printStackTrace();
}
if (sc != null) {
sc.close();
}
return true;
}
public int count() {
int count = artists.size();
return count;
}
public int count(String genre) {
}
}
What I'm testing with:
public class ArtistTest
{
public static void main(String[] args)
{
Artists artists = new Artists();
System.out.println(artists.count() + " artists in the list");
System.out.println(artists.count("Rock") + " rock artists in the list\n");
System.out.println("File opened successfully? " + artists.readArtists("artists30.txt"));
System.out.println("\n" + artists.count() + " artists in the list");
System.out.println(artists.count("Rock") + " rock artists in the list");
System.out.println(artists.count("R&B") + " R&B artists in the list");
}
}
答案1
得分: 1
这是您要求的翻译内容:
我是老派的。所有那些新的 Streams 相关的东西让我感到晕头转向。我喜欢保持事情简单。我达到您想要的目标的方法是做两件简单的事情:
1)定义一个表示每位艺术家信息的 Artist 对象。此对象知道如何根据数据文件中的一行构造自身。
2)在读取艺术家的同时,创建一个按流派分类的第二个索引,该索引将为每个流派提供一个艺术家列表。
我做的另一件事是使事情变得非静态,这样您实际上可以实例化一个 Artists 对象,以防您希望拥有多个艺术家列表。
以下是我的版本:
import java.util.*;
import java.io.File;
import java.util.Scanner;
public class Artists {
public class Artist {
public String name;
public String genre;
public Artist(String line) {
String[] parts = line.trim().split("\\s+");
name = parts[0];
genre = parts[1];
}
}
private List<Artist> artists = new ArrayList<>();
private Map<String, List<Artist>> genres = new HashMap<>();
public boolean readArtists(String fileName) {
Scanner sc = null;
try {
File file = new File(fileName);
if (file.createNewFile()) {
System.out.println("err " + fileName);
return false;
}
sc = new Scanner(file);
while (sc.hasNextLine()) {
// 将行转换为 Artist 对象
Artist artist = new Artist(sc.nextLine());
// 将其添加到主要的艺术家列表中
artists.add(artist);
// 将其添加到按流派分类的索引中
if (!genres.containsKey(artist.genre))
genres.put(artist.genre, new ArrayList<>());
genres.get(artist.genre).add(artist);
}
} catch (Exception e) {
e.printStackTrace();
}
if (sc != null) {
sc.close();
}
return true;
}
public int count() {
return artists.size();
}
public int count(String genre) {
if (genres.containsKey(genre))
return genres.get(genre).size();
return 0;
}
public static void main(String[] args) {
Artists artists = new Artists();
String filepath = "/tmp/artists30.txt";
if (artists.readArtists(filepath)) {
System.out.printf("Artist Count: %d\n", artists.count());
System.out.printf("Rock Artist Count: %d\n", artists.count("Rock"));
}
else {
System.out.printf("Failed to read artists file '%s'\n", filepath);
}
}
}
示例数据:
Abba Pop
Beethoven Classical
Rush Rock
Aerosmith Rock
Mozart Classical
AC/DC Rock
Yes Rock
结果:
艺术家数量:7
摇滚音乐家数量:4
英文:
I'm old school. All that new Streams stuff spins my head around. I like to keep things simple. My way to what you want is to do two simple things:
-
Define an Artist object that will represent the info on each artist. This object knows how to construct itself from a line in the data file.
-
While reading in the artists, create a second by-genre index that will give you a list of artists for each genre.
The other thing I did was make things non-static, so you actually instantiate an Artists object, in case you ever wanted to have multiple lists of artists.
Here's my rendition:
import java.util.*;
import java.io.File;
import java.util.Scanner;
public class Artists {
public class Artist {
public String name;
public String genre;
public Artist(String line) {
String[] parts = line.trim().split("\\s+");
name = parts[0];
genre = parts[1];
}
}
private List<Artist> artists = new ArrayList<>();
private Map<String, List<Artist>> genres = new HashMap<>();
public boolean readArtists(String fileName) {
Scanner sc = null;
try {
File file = new File(fileName);
if (file.createNewFile()) {
System.out.println("err " + fileName);
return false;
}
sc = new Scanner(file);
while (sc.hasNextLine()) {
// Turn the line into an Artist object
Artist artist = new Artist(sc.nextLine());
// Add it to the main list of artists
artists.add(artist);
// Add it to the per-genre index
if (!genres.containsKey(artist.genre))
genres.put(artist.genre, new ArrayList<>());
genres.get(artist.genre).add(artist);
}
} catch (Exception e) {
e.printStackTrace();
}
if (sc != null) {
sc.close();
}
return true;
}
public int count() {
return artists.size();
}
public int count(String genre) {
if (genres.containsKey(genre))
return genres.get(genre).size();
return 0;
}
public static void main(String[] args) {
Artists artists = new Artists();
String filepath = "/tmp/artists30.txt";
if (artists.readArtists(filepath)) {
System.out.printf("Artist Count: %d\n", artists.count());
System.out.printf("Rock Artist Count: %d\n", artists.count("Rock"));
}
else {
System.out.printf("Failed to read artists file '%s'\n", filepath);
}
}
}
Sample Data:
Abba Pop
Beethoven Classical
Rush Rock
Aerosmith Rock
Mozart Classical
AC/DC Rock
Yes Rock
Result:
Artist Count: 7
Rock Artist Count: 4
答案2
得分: 0
以下是翻译好的代码部分:
只要您的映射为"artist" + "space" + "genre",您可以尝试以下代码。这将创建一个映射,其中所有流派都作为键,值是该流派的相应计数。
class Grouper {
public static void main(String[] args) {
var grouper = new Grouper();
grouper.groupByGenre();
}
void groupByGenre() {
List<String> musicCollection = List.of("Kid Rock", "Hello Rock", "Beethoven Classical");
var collection = musicCollection.stream()
.map(entry -> entry.split(" "))
.filter(strings -> strings.length == 2)
.map(strings -> new MusicCollection(strings[0], strings[1]))
.collect(Collectors.groupingBy(MusicCollection::getGenre, Collectors.counting()));
System.out.println(collection);
}
}
class MusicCollection {
private final String artist;
private final String genre;
public MusicCollection(String artist, String genre) {
this.artist = artist;
this.genre = genre;
}
public String getArtist() {
return artist;
}
public String getGenre() {
return genre;
}
}
EDIT:
为了使它更简单,将您的计数方法替换为以下内容:
public int count(String genre)
{
return (int) artists.stream()
.map(entry -> entry.split(" "))
.filter(strings -> strings.length == 2)
.map(strings -> strings[1])
.filter(value -> Objects.equals(value, genre))
.count();
}
请注意,已经将代码中的HTML实体编码转换为正常文本。
英文:
Well as long as your mapping will be "artist" + "space" + "genre" you could try the following code. This creates a map with all the genres as key, and the value is the respective count for the genre.
class Grouper {
public static void main(String[] args) {
var grouper = new Grouper();
grouper.groupByGenre();
}
void groupByGenre() {
List<String> musicCollection = List.of("Kid Rock", "Hello Rock", "Beethoven Classical");
var collection = musicCollection.stream()
.map(entry -> entry.split(" "))
.filter(strings -> strings.length == 2)
.map(strings -> new MusicCollection(strings[0], strings[1]))
.collect(Collectors.groupingBy(MusicCollection::getGenre, Collectors.counting()));
System.out.println(collection);
}
}
class MusicCollection {
private final String artist;
private final String genre;
public MusicCollection(String artist, String genre) {
this.artist = artist;
this.genre = genre;
}
public String getArtist() {
return artist;
}
public String getGenre() {
return genre;
}
}
EDIT:
To make it simpeler, replace your count method with the following:
public int count(String genre)
{
return (int) artists.stream()
.map(entry -> entry.split(" "))
.filter(strings -> strings.length == 2)
.map(strings -> strings[1])
.filter(value -> Objects.equals(value, genre))
.count();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论