Java 使用集合或my函数计算ArrayList中对象的出现次数

Java 使用集合或my函数计算ArrayList中对象的出现次数,java,object,collections,arraylist,find-occurrences,Java,Object,Collections,Arraylist,Find Occurrences,我有一个FlowerClass对象的ArrayList。每个FlowerClass对象都有一个名称。我想通过ArrayList数一数。我想显示每个的数量。因此,如果我有三个名为Rose的FlowerClass对象,两个名为Daffodil,一个名为Tulip…我想显示以下内容: public static void displayFlowers() { for (String name : flowerCount.keySet()) { //sea

我有一个FlowerClass对象的ArrayList。每个FlowerClass对象都有一个名称。我想通过ArrayList数一数。我想显示每个的数量。因此,如果我有三个名为Rose的FlowerClass对象,两个名为Daffodil,一个名为Tulip…我想显示以下内容:

    public static void displayFlowers() {
        for (String name : flowerCount.keySet()) {
            //searchFlower(name);
            System.out.println("Found " + flowerCount.get(name) + " " + name);
        }
    }
  • 找到3朵玫瑰
  • 发现了3朵水仙花
  • 找到3朵郁金香
到目前为止,我已经使用我制作的两个函数正确地计算了它。问题是我遍历了整个ArrayList…所以它会不止一次地向我显示结果。例如,如果用户添加3朵玫瑰和2朵水仙花…输出如下:

  • 找到3朵玫瑰
  • 找到3朵玫瑰
  • 找到3朵玫瑰
  • 发现了2朵水仙花
  • 发现了2朵水仙花
我知道代码为什么会这样做,但我不知道如何删除重复的输出。我也不知道如何正确地实现集合。我以前在字符串的ArrayList上使用过Collections…它很有效。但这次我将在对象的ArrayList上使用集合,我想检查每个特定名称的频率。以下是主要课程:

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;

public class MainClass {

    static ArrayList<FlowerClass> flowerPack = new ArrayList<FlowerClass>();


    public static void main(String[] args){
        Scanner input = new Scanner(System.in);

        while(true){
            System.out.println("1. Add flower to flowerpack.");
            System.out.println("2. Remove flower from the flowerpack.");
            System.out.println("3. Search for a flower in the flowerpack."); 
            System.out.println("4. Display the flowers in the flowerpack.");
            System.out.println("5. Exit the program.");

            int userChoice = input.nextInt();

            switch(userChoice){
            case 1:
                addFlower();
                break;
            case 2:
                searchFlower();
                break;
            case 3:
                displayFlowers();
                break;
            case 4:
                    System.out.println("Goodbye!");
                System.exit(0);
            }
        }
    }

    public static void addFlower(){
        if (FlowerClass.numberFlowers() == 25){
            System.out.println("There are 25 flowers in the flowerpack. Remove at least one in order to add more.");
            return;
        }
        Scanner input = new Scanner(System.in);
        System.out.println("What is the flower's name?");
        String desiredName = input.nextLine();
        System.out.println("What is the flower's color?");
        String desiredColor = input.nextLine();
        System.out.println("How many thorns does it have?");
        Scanner input2 = new Scanner(System.in);
        int desiredThorns = input2.nextInt();
        System.out.println("What does it smell like?");
        String desiredSmell = input.nextLine();
        flowerPack.add(new FlowerClass(desiredName, desiredColor, desiredThorns, desiredSmell));
    }

    public static void searchFlower(){
        System.out.println("Enter the flower you want to search for.");
        Scanner input = new Scanner(System.in);
        String userChoice = input.nextLine();
        int occurrences  = 0;

        for (FlowerClass flower: flowerPack){
            String name = flower.getName();
            if (userChoice.equals(name)){
                occurrences++;
            }

            else if(occurrences == 0){
                System.out.println("Match not found.");
                return;
            }
        }

        System.out.println("Found " + occurrences + " " + userChoice);
    }

    public static void searchFlower(String desiredFlower){
        int occurrences = 0;

        String userChoice = desiredFlower;
        for (FlowerClass flower: flowerPack){
            String name = flower.getName();
            if (userChoice.equals(name)){
            occurrences++;
            }
        }

        System.out.println("Found " + occurrences + " " + userChoice);
    }

    public static void displayFlowers(){
        int repeats = 0;

        /*for (FlowerClass flower: flowerPack){
            System.out.println(flower.getName());
        }
        System.out.println("Number of flowers in pack: " + FlowerClass.numberFlowers());*/

            //int occurrences = Collections.frequency(flowerPack, name);
            //System.out.println(name + ": " + occurrences);
        for (FlowerClass flower: flowerPack){
            String name = flower.getName();
            searchFlower(name);
        }
    }
}
如果您查看我在main类中的最后一个函数,您将看到我注释掉了尝试实现Collections.frequency的方式。我还尝试创建一个多维字符串数组,存储花的名称以及数组中花的数量。这是正确的计数,但我不知道如何显示计数旁边的名字。它变得非常混乱,所以我暂时放弃了尝试,转而尝试其他两种选择。如果我能找到一种方法删除重复的输出行(或者如果我能找到一种方法让集合工作),那么我就不需要修补多维数组

任何提示都将不胜感激。谢谢你抽出时间

您可以将您的花放入
集合
。但我能想到的最简单的解决办法是给你的花分类。因此,首先,实现一个

然后你的
for
循环需要是这样的(停止搜索同一朵花)

String lastName=null;
对于(int i=0;i
有趣的代码,但它不像我那样工作

在本例中,正如您所做的那样,您需要跟踪您已经遇到的花名:

public static void displayFlowers(){
    //int repeats = 0;
    List<String> displayedFlowerTypes = new ArrayList<String>();
    for (FlowerClass flower: flowerPack){
        String name = flower.getName();
        if(!displayedFlowerTypes.contains(name))
        {
            displayedFlowerTypes.add(name);
            searchFlower(name);
        }
    }
}

使用迭代器迭代arraylist迭代器itr=al.iterator();而(itr.hasNext())则是完美的。您是否有比较器的首选资源?我想读更多关于他们的书。您的解决方案非常有效。我做了一个新的类叫做FlowerComparator。但它不让我让它保持静止。必须清除静电。因此标题是:公共类FlowerComparator实现ComparatorTanks以获得帮助。不幸的是,我还没有准备好使用地图。我正在为一个中期项目(这不是中期项目)练习,我相信我们可以使用数组和ArrayList,所以我正在努力为此做准备。不过,我真的很喜欢你写的新ArrayList。这正是我需要的,我可以说它已经起作用了。完美答案。我也喜欢另一个人的答案,但这不需要另一个类,它使用的是我已经练习过的ArrayList。我要试着实现这个,我成功地实现了。我喜欢它。我不需要整理任何东西,我可以移除和添加更多的花,到目前为止没有任何问题。真的很棒。谢谢你的帮助。我还将研究地图解决方案。两种解决方案中的任何一种在速度方面是否明显更好?我不需要担心速度,但我很好奇,在搜索特定内容时,地图是否比ArrayList快。我很高兴它按您的预期工作!:)我喜欢排序解决方案,因为它是有意义的,但它不是我想在期中考试时写在纸上的东西,因为“无误”和直观解决方案的速度是必须的。我的两种方法之间的关键区别是,对于所有类型的显示,列表版本需要在整个列表中迭代次数与花类型的次数相同,以获得计数,即O(N);但是映射已经将信息存储在给定键的值中,因此可以使用O(1)而不是列表迭代进行单个操作。从技术上讲,如果列表中有许多花,那么列表方法将明显慢于映射解决方案(以获得每种类型的花数)。但是有了25朵花,差别并没有那么大。
FlowerComparator flowerComparator = new FlowerComparator();
Collections.sort(flowerPack, flowerComparator);
String lastName = null;
for (int i = 0; i < flowerPack.size(); i++){
  FlowerClass flower = flowerPack.get(i);
  String name = flower.getName();
  if (lastName == null || !lastName.equals(name)) {
    lastName = name;
    searchFlower(name); // or return the number found, and then add that count to i.
  }
 }
public static void displayFlowers(){
    //int repeats = 0;
    List<String> displayedFlowerTypes = new ArrayList<String>();
    for (FlowerClass flower: flowerPack){
        String name = flower.getName();
        if(!displayedFlowerTypes.contains(name))
        {
            displayedFlowerTypes.add(name);
            searchFlower(name);
        }
    }
}
public class MainClass {

static List<FlowerClass> flowerPack = new ArrayList<FlowerClass>();
static Map<String, Integer> flowerCount = new HashMap<String, Integer>();

public static void addFlower() {
    if (FlowerClass.numberFlowers() == 25) {
        System.out.println("There are 25 flowers in the flowerpack. Remove at least one in order to add more.");
        return;
    }
    Scanner input = new Scanner(System.in);
    System.out.println("What is the flower's name?");
    String desiredName = input.nextLine();
    System.out.println("What is the flower's color?");
    String desiredColor = input.nextLine();
    System.out.println("How many thorns does it have?");
    Scanner input2 = new Scanner(System.in);
    int desiredThorns = input2.nextInt();
    System.out.println("What does it smell like?");
    String desiredSmell = input.nextLine();
    flowerPack.add(new FlowerClass(desiredName, desiredColor, desiredThorns, desiredSmell));
    if(!flowerCount.containsKey(desiredName))
    {
        flowerCount.put(desiredName, 1);
    }
    else
    {
        int currentCount = flowerCount.get(desiredName);
        flowerCount.put(desiredName, currentCount+1));
    }
}
    public static void displayFlowers() {
        for (String name : flowerCount.keySet()) {
            //searchFlower(name);
            System.out.println("Found " + flowerCount.get(name) + " " + name);
        }
    }