打印具有最大整数键的 HashMap 字符串值

Printing a HashMap String value with largest Integer Key

我只是在 Java 尝试创建一个程序来显示股票的一些基本信息。到目前为止,我的代码如下所示:

库存class:

import java.util.Scanner;

public class Stock {
    private String company_name;
    private String ticker;
    private String category;
    private Double price;

    public Stock()
    {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Please enter company name: ");
        this.company_name = scanner.nextLine();
        System.out.print("Please enter stock TICKER: ");
        this.ticker = scanner.nextLine();
        System.out.print("Please enter the stock's category: ");
        this.category = scanner.nextLine();
        System.out.print("Please enter stock's current price: ");
        this.price = scanner.nextDouble();
    }
    public Stock(String cn, String tic, String cat, Double p)
    {
        this.company_name = cn;
        this.ticker = tic;
        this.category = cat;
        this.price = p;
    }

    public String getCompany_name() {
        return company_name;
    }

    public void setCompany_name(String company_name) {
        this.company_name = company_name;
    }

    public String getTicker() {
        return ticker;
    }

    public void setTicker(String ticker) {
        this.ticker = ticker;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }
}

和我的股票清单 class

import java.util.*;

public class StockList {

    /* StockList's Array List */
    private final ArrayList<Stock> stock_list = new ArrayList<Stock>();

    /**
     * Getter for StockList's Array List
     * @return StockList's Array List
     */
    public ArrayList<Stock> getStock_list() {
        return stock_list;
    }

    /**
     * Method to add stock
     * @param stock is the stock you want to be added to array list
     */
    public void add(Stock stock)
    {
        stock_list.add(stock);
    }

    /**
     * Method to create a Stock object AND THEN add it to Array List
     */
    public void add()
    {
        Stock stock = new Stock();
        this.add(stock);
    }

    /**
     * Have the user give a company name, find the matching name from the StockList Array List
     * and then delete it, if it's there. Otherwise, return a friendly message telling the user
     * that the stock was not found.
     */
    public void delete()
    {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter the company name of the stock you wish to remove.");
        String company_name = scanner.nextLine();
        Iterator<Stock> iter = this.stock_list.iterator();
        while(iter.hasNext())
        {
            if(iter.next().getCompany_name().equals(company_name))
            {
                System.out.println(company_name + " was successfully removed.");
                iter.remove();
                return;
            }
        }
        System.out.println(company_name + " was not found in your list of current stocks.");
    }

    /**
     * Simple print method for the StockList Array List
     */
    public void print()
    {
        if(stock_list.isEmpty())
        {
            System.out.println("Your list is empty.");
            return;
        }
        System.out.println("=========================================");
        for (Stock value : stock_list) {
            System.out.println("Company: " + value.getCompany_name());
            System.out.println("Ticker: " + value.getTicker());
            System.out.println("Category: " + value.getCategory());
            System.out.println("Price: $" + value.getPrice());
        }
        System.out.println("=========================================");
    }


    public void sum_up_list() {
        double total_investment_price = 0.0;
        String most_invested_category;

        Map<String, Integer> category_and_count = new HashMap<String, Integer>();
        /* Get the categories and their percentages */
        for (Stock value : stock_list) {
            Integer j = category_and_count.get(value);
            category_and_count.put(value.getCategory(), (j == null) ? 1 : j + 1);
            total_investment_price += value.getPrice();
        }

        String max_cat = "NULL";
        int max_cat_count = 0;
        for (Map.Entry<String, Integer> val : category_and_count.entrySet()) {
            if (category_and_count.get(val.getKey()) >= max_cat_count)
            {
                max_cat = val.getKey();
                max_cat_count = val.getValue();
            }
        }


        System.out.println("Total investments $" + total_investment_price);
        System.out.println("The category I'm most invested in is " + max_cat +
                " with " + max_cat_count + " stocks in this category.");

    }
}

但现在我正在努力使用 sum_up_list() 方法。我想做的是创建一个 HashMap,其中包含每只股票的类别以及该特定类别每次在我的 stock_list 上出现的次数。现在它保留类别名称但计数已关闭..

基本上,我要做的是遍历 stock_list 数组列表,并针对每个唯一类别将其添加到哈希图中,使用类别作为哈希图的字符串键。然后以后每次发现 category/key 时,都会将 hashmap 键的值更新 1。如果这有意义?我发现现在很难用语言表达..

这是我现在得到的一些输出文本:

Please enter company name: Costco
Please enter stock TICKER: COST
Please enter the stock's category: Retail
Please enter stock's current price: 312.18
Please enter company name: Amazon
Please enter stock TICKER: AMZ
Please enter the stock's category: Tech
Please enter stock's current price: 3002.40
Please enter company name: AirBNB
Please enter stock TICKER: BNB
Please enter the stock's category: Tech
Please enter stock's current price: 142.50
Total investments 57.08
The category I'm most invested in is Tech with 1 stocks in this category.

我希望最后的输出行改为:

The category I'm most invested in is Tech with **2** stocks in this category.

编辑: 我在下面使用了 njzk2 的合并解决方案,它也能按我的需要工作!谢谢您的帮助。这是更新后的 sum_up_list() 方法,它是我所有麻烦的根源:

    public void sum_up_list() {
        double total_investment_price = 0.0;
        String most_invested_cat = "NULL";
        int cat_count = 0;

        Map<String, Integer> category_and_count = new HashMap<String, Integer>();
        /* Get the categories and their percentages */
        for (Stock value : stock_list) {
            category_and_count.merge(value.getCategory(), 1, Integer::sum);
            total_investment_price += value.getPrice();
        }

        for (Map.Entry<String, Integer> val : category_and_count.entrySet())
        {
            if(val.getValue() >= cat_count)
            {
                most_invested_cat = val.getKey();
                cat_count = val.getValue();
            }
        }
        
        System.out.println("Total investments $" + total_investment_price);
        System.out.println("The category I'm most invested in is " + most_invested_cat +
                " with " + cat_count + " stocks in this category.");

    }
}

主要问题是获得正确的计数:category_and_count.get(value); 应该是 category_and_count.get(value.getCategory());

使用 merge 方法更容易完成:

    for (Stock value : stock_list) {
        category_and_count.merge(value.getCategory(), 1, Integer::sum);
        total_investment_price += value.getPrice();
    }

或者更简单的 groupingBy:

category_and_count = stock_list
    .stream()
    .groupingBy(Stock::getCategory, Collectors.counting());

total_investment_price = stock_list
    .stream()
    .collect(Collectors.summingInt(Stock::getPrice));

更改以下代码

max_cat = val.getKey();

  if(max_cat_count < val.getValue()) 
   {
      max_cat_count = val.getValue(); 
      max_cat = val.getKey();
   }