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

Java 打印具有最大整型键的HashMap字符串值,java,arraylist,hashmap,Java,Arraylist,Hashmap,我只是在玩Java,试图创建一个可以显示股票基本信息的程序。。到目前为止,我的代码如下所示: 股票类别: import java.util.Scanner; public class Stock { private String company_name; private String ticker; private String category; private Double price; public Stock() {

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

股票类别:

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;
    }
}
还有我的股票列表课

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.");

    }
}
我希望最终的输出行改为:

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.");

    }
}
公共作废汇总表(){
双倍总投资价格=0.0;
字符串most_invested_cat=“NULL”;
int cat_计数=0;
映射类别和计数=新HashMap();
/*获取类别及其百分比*/
用于(库存价值:库存清单){
category和count.merge(value.getCategory(),1,Integer::sum);
总投资价格+=value.getPrice();
}
对于(Map.Entry val:category_和_count.entrySet())
{
如果(val.getValue()>=类别计数)
{
most_invested_cat=val.getKey();
cat_count=val.getValue();
}
}
System.out.println(“总投资$”+总投资价格);
System.out.println(“我投资最多的类别是”+投资最多的类别+
“带有“+类别计数+”这类股票。”);
}
}

主要问题是获得正确的计数:
category\u和\u count.get(value)
应该是
category_和_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));

主要问题是获取正确的计数:
category\u和\u count.get(value)
应该是
category_和_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(最大cat\u计数
更改以下代码

max_cat = val.getKey();

if(最大cat\u计数
类别和计数。获取(值)不应编译此
类别和计数。获取(值)不应编译