使用数组作为HashMapJava的键

使用数组作为HashMapJava的键,java,arrays,hashmap,key,Java,Arrays,Hashmap,Key,我有一个方法,将一些值(从excel文件中获取)放入一个以数组为键的hashmap中 public HashMap<List<String>, List<String[]>> sbsBusServiceDataGnr() throws IOException { System.out.println(engine.txtY + "Processing HashMap " + "sbsBusServiceData..." + e

我有一个方法,将一些值(从excel文件中获取)放入一个以数组为键的hashmap中

public HashMap<List<String>, List<String[]>> sbsBusServiceDataGnr() throws 
    IOException
{
    System.out.println(engine.txtY + "Processing HashMap "
        + "sbsBusServiceData..." + engine.txtN);
    int counterPass = 0, counterFail = 0, stopCounter = 0;
    String dataExtract, x = "";
    String[] stopInfo = new String[3];
    List<String[]> stopsData = new ArrayList<String[]>();
    List<String> serviceNum = new Vector<String>();

    HashMap<List<String>, List<String[]>> sbsBusServiceData = 
        new HashMap<List<String>, List<String[]>>();
    String dataPath = this.dynamicPathFinder(
        "Data\\SBS_Bus_Routes.csv");
    BufferedReader sbsBusServiceDataPop = new BufferedReader(
        new FileReader(dataPath));

    sbsBusServiceDataPop.readLine();
    //Skips first line
    while ((dataExtract = sbsBusServiceDataPop.readLine()) != null) {
        try {
            String[] dataParts = dataExtract.split(",", 5);
            if (!dataParts[4].equals("-")){
                if (Double.parseDouble(dataParts[4]) == 0.0){
                    sbsBusServiceData.put(serviceNum, stopsData);
                    String serviceNum1 = "null", serviceNum2 = "null";
                    if(!serviceNum.isEmpty()){
                        serviceNum1 = serviceNum.get(0);
                        serviceNum2 = serviceNum.get(1);
                    }
                    System.out.println("Service Number " + serviceNum1 
                        + ":" + serviceNum2 + " with " + stopCounter 
                        + " stops added.");
                    stopCounter = 0;
                    //Finalizing previous service

                    serviceNum.Clear();
                    serviceNum.add(0, dataParts[0]);
                    serviceNum.add(1, dataParts[1]);
                    //Adding new service
                }
            }
            stopInfo[0] = dataParts[2];
            stopInfo[1] = dataParts[3];
            stopInfo[2] = dataParts[4];
            stopsData.add(stopInfo);
            //Adding stop to service

            stopCounter++;
            counterPass++;
            }
        catch (Exception e) {
            System.out.println(engine.txtR + "Unable to process "
                + dataExtract + " into HashMap sbsBusServiceData." 
                + engine.txtN + e);
            counterFail++;
        }
    }
    sbsBusServiceDataPop.close();

    System.out.println(engine.txtG + counterPass + " number of lines"
        + " processed into HashMap sbsBusServiceData.\n" + engine.txtR
        + counterFail + " number of lines failed to process into "
        + "HashMap sbsBusServiceData.");

    return sbsBusServiceData;
}
//Generates sbsBusServiceDataGnr HashMap : 15376 Data Rows
//HashMap Contents: {ServiceNumber, Direction}, 
//    <{RouteSequence, bsCode, Distance}>
public HashMap sbsBusServiceDataGnr()抛出
IOException
{
System.out.println(engine.txtY+“处理哈希映射”
+“SBSBUServiceData…”+engine.txtN);
int计数器=0,计数器=0,计数器=0;
字符串dataExtract,x=“”;
字符串[]stopInfo=新字符串[3];
List stopsData=new ArrayList();
List serviceNum=new Vector();
HashMap sbsBusServiceData=
新的HashMap();
String dataPath=this.dynamicPathFinder(
“Data\\SBS_Bus_Routes.csv”);
BufferedReader sbsBusServiceDataPop=新的BufferedReader(
新文件读取器(数据路径));
sbsBusServiceDataPop.readLine();
//跳过第一行
而((dataExtract=sbsbsbusservicedatapop.readLine())!=null){
试一试{
字符串[]dataParts=dataExtract.split(“,”,5);
如果(!dataParts[4]。等于(“-”){
if(Double.parseDouble(dataParts[4])==0.0){
sbsbuservicedata.put(serviceNum,stopsData);
字符串serviceNum1=“null”,serviceNum2=“null”;
如果(!serviceNum.isEmpty()){
serviceNum1=serviceNum.get(0);
serviceNum2=serviceNum.get(1);
}
System.out.println(“服务编号”+serviceNum1
+“:“+serviceNum2+”和“+stopCounter”
+(详情请参阅会议过程正式纪录英文本);
停止计数器=0;
//完成以前的服务
serviceNum.Clear();
serviceNum.add(0,dataParts[0]);
serviceNum.add(1,dataParts[1]);
//添加新服务
}
}
stopInfo[0]=dataParts[2];
stopInfo[1]=数据部件[3];
stopInfo[2]=数据部件[4];
stopsData.add(stopInfo);
//为服务添加站点
停止计数器++;
反传++;
}
捕获(例外e){
System.out.println(engine.txtR+“无法处理”
+dataExtract+“到HashMap sbsBusServiceData中。”
+发动机(txtN+e);
反邮件++;
}
}
sbsBusServiceDataPop.close();
System.out.println(engine.txtG+反程+“行数”
+“已处理为HashMap sbsBusServiceData。\n”+engine.txtR
+counterFail+“无法处理到的行数”
+“HashMap sbsBusServiceData.”);
返回sbsbuservicedata;
}
//生成sbsBusServiceDataGnr HashMap:15376数据行
//HashMap内容:{ServiceNumber,Direction},
//    
此方法用于将值放入hashmap,但当我尝试调用它时,似乎无法从hashmap中获取任何值—始终存在nullpointerexception

List<String> sbsTest = new Vector<String>();
    sbsTest.add(0, "10");
    sbsTest.add(1, "1");
    System.out.println(sbsBusServiceData.get(sbsTest));
    try{
        List<String[]> sbsServiceResults = sbsBusServiceData.get(sbsTest);
        System.out.println(sbsServiceResults.size());
        String x = sbsServiceResults.get(1)[0];
        System.out.println(x);
    } catch(Exception e){
        System.out.println(txtR + "No data returned" + txtN + e);
    }
List sbsTest=new Vector();
SBST.添加(0,“10”);
SBST.添加(1,“1”);
System.out.println(sbusservicecdata.get(sbsTest));
试一试{
List sbsServiceResults=sbsBusServiceData.get(sbsTest);
System.out.println(sbsServiceResults.size());
字符串x=sbsServiceResults.get(1)[0];
系统输出println(x);
}捕获(例外e){
System.out.println(txtR+“无数据返回”+txtN+e);
}
这是im从中读取数据的文件示例:


如何让hashmap返回我想要的值?

数组不适合作为
hashmap
s中的键,因为数组不重写
对象的
equals
hashCode
方法(这意味着包含完全相同元素的两个不同数组实例将被
HashMap
视为不同的键)


替代方法是使用
列表
而不是
字符串[]
作为
哈希映射
的键,或者使用
树映射
,并将自定义的
比较器
传递给构造函数。

如果您具有固定的数组大小,那么我发布的示例可能会很有用。 在这里,我创建了两个对象,一个是食物,另一个是产品。 这里的食物对象是使用和添加的方法来获取字符串数组

public class Product {

private String productName;
private String productCode;

    public Product(String productName, String productCode) {
        this.productName = productName;
        this.productCode = productCode;
    }

    public String getProductName() {
        return productName;
    }
    public void setProductName(String productName) {
        this.productName = productName;
    }
    public String getProductCode() {
        return productCode;
    }
    public void setProductCode(String productCode) {
        this.productCode = productCode;
   }    
}
食品模型类:用作对象而不是字符串[],并实现字符串[]功能

public class Food implements Comparable<Food> {

private String type;
private String consumeApproach;

    public Food(String type, String consumeApproach) {
        this.type = type;
        this.consumeApproach = consumeApproach;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getConsumeApproach() {
        return consumeApproach;
    }

    public void setConsumeApproach(String consumeApproach) {
        this.consumeApproach = consumeApproach;
    }

    public String[] FoodArray() {
        return new String[] { this.type, this.consumeApproach };
    }
//Implement compareTo method as you want.
    @Override
    public int compareTo(Food o) {
        return o.getType().compareTo(this.type);
    }
}
公共级食品{
私有字符串类型;
私有字符串方法;
公共食品(字符串类型、字符串方法){
this.type=type;
this.consumerapproach=consumerapproach;
}
公共字符串getType(){
返回类型;
}
公共void集合类型(字符串类型){
this.type=type;
}
公共字符串getconsumerapproach(){
回归分析法;
}
公共void setconsumerapproach(字符串consumerapproach){
this.consumerapproach=consumerapproach;
}
公共字符串[]FoodArray(){
返回新字符串[]{this.type,this.consumerapproach};
}
//根据需要实现compareTo方法。
@凌驾
公共内部比较(食品o){
返回o.getType().compareTo(this.type);
}
}
使用HashMap示例

public class HashMapKeyAsArray {

public static void main(String[] args) {
    HashMap<Food,List<Product>> map = dataSetLake();
    map.entrySet().stream().forEach(m -> {
        String[] food = m.getKey().FoodArray();
        Arrays.asList(food).stream().forEach(f->{
            System.out.print(f + "       ");
        });
        System.out.println();
        List<Product> list = m.getValue();
        list.stream().forEach(e -> {
            System.out.println("Name:" + e.getProductName() + "     Produc Code:" + e.getProductCode());
        });
        System.out.println();
    });
}

private static HashMap<Food,List<Product>> dataSetLake(){
    HashMap<Food,List<Product>> data = new HashMap<>();

    List<Product> fruitA = new ArrayList<>();

    fruitA.add(new Product("Apple","123"));
    fruitA.add(new Product("Banana","456"));
    List<Product> vegetableA = new ArrayList<>();
    vegetableA.add(new Product("Potato","999"));
    vegetableA.add(new Product("Tomato","987"));

    List<Product> fruitB = new ArrayList<>();

    fruitB.add(new Product("Apple","123"));
    fruitB.add(new Product("Banana","456"));
    List<Product> vegetableB = new ArrayList<>();
    vegetableB.add(new Product("Potato","999"));
    vegetableB.add(new Product("Tomato","987"));

    Food foodA = new Food("Fruits","Read To Eat");
    Food foodB = new Food("Vegetables","Need To Cook");
    Food foodC = new Food("VegetablesC","Need To Cook C");


    data.put(foodA, fruitB);
    data.put(foodB, vegetableB);

    data.put(foodA, fruitA);
    data.put(foodC, vegetableA);

    return data;
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeMap;

public class TreeMapKeyAsArray {
    public static void main(String[] args) {
        TreeMap<Food, List<Product>> map = dataSetLake();
        map.entrySet().stream().forEach(m -> {
        String[] food = m.getKey().FoodArray();
        Arrays.asList(food).stream().forEach(f->{
            System.out.print(f + "       ");
        });
        System.out.println();
        List<Product> list = m.getValue();
        list.stream().forEach(e -> {
            System.out.println("Name:" + e.getProductName() + "     Produc Code:" + e.getProductCode());
        });
        System.out.println();
    });
}

private static TreeMap<Food, List<Product>> dataSetLake() {
    TreeMap<Food, List<Product>> data = new TreeMap<>();

    List<Product> fruitA = new ArrayList<>();

    fruitA.add(new Product("Apple", "123"));
    fruitA.add(new Product("Banana", "456"));
    List<Product> vegetableA = new ArrayList<>();
    vegetableA.add(new Product("Potato", "999"));
    vegetableA.add(new Product("Tomato", "987"));

    List<Product> fruitB = new ArrayList<>();

    fruitB.add(new Product("Apple", "123"));
    fruitB.add(new Product("Banana", "456"));
    List<Product> vegetableB = new ArrayList<>();
    vegetableB.add(new Product("Potato", "999"));
    vegetableB.add(new Product("Tomato", "987"));

    Food foodA = new Food("Fruits", "Read To Eat");
    Food foodB = new Food("Vegetables", "Need To Cook");

    data.put(foodA, fruitB);
    data.put(foodB, vegetableB);

    data.put(foodA, fruitA);
    data.put(foodB, vegetableA);
    return data;
    }
}
公共类HashMapKeyAsArray{
公共静态void main(字符串[]args){
HashMap map=dataSetLake();
map.entrySet().stream().forEach(m->{
字符串[]food=m.getKey().FoodArray();
Arrays.asList(food.stream().forEach(f->{
系统输出打印(f+“”);
});
System.out.println();
List=m.getValue();
list.stream().forEach(e->{
System.out.println(“名称:+e.getProductName()+”产品代码:+e.getProductCode());
});
System.out.println();
});
}
私有静态HashMap dataSetLake(){
HashMap数据=新的HashMap();
List FROUTURA=新的ArrayList();
添加(新产品(“应用程序”)