2017-10-06 94 views
-3

我有两个数组如何将数组和地图结合起来并与之结合?

String[] names = {“bob”, “rob”}; //There are multiple arrays for various scenarios names1, names2 and so on… 
String[] features = {“age”, “weight”}; //There are multiple array for various scenarios features1 features2 and so on… 

,并在其中有
年龄,体重,性别,职业键和值类HashMap中......

我得到的值从这样的:

public ClassToGetValues (String name) {  

public String getValue(String key) { 
       return map.get(key); 
      } 

    private void buildMap(Paramenter1 paramenter1, Paramenter2, paramenter2) { 
       map.put("name", someFunction()); 
      map.put(.... 
     } 
    } 

我使用这些阵列和地图用于打印以下:
鲍勃30yr 160磅
抢劫4 0yr 170lbs

private static void printMethod(String[] names, String[] features) { 

     for (String name : names) { 
      ClassToGetValues classToGetValues = new ClassToGetValues(name); 
      for (String feature : features) { 
       System.out.print(classToGetValues.getValue(feature) + " "); 

      } 
      System.out.println(); 
     } 

    } 

现在我想创建一个像

方法1

public String criteriaOne(int age, int weight) { 
     if (age > 35 && weight > 160) { 
      // "Do something"; 
     } 
     return names; 
    } 

方法2

public String criteriaTwo(int age, String gender) { 
      if (age <70 && gender == “male”) { 
       // "Do something"; 
      } 
      return names; 
     } 

我做我在创造这些方法启动一些方法?

+2

Person的数据Java是一种面向对象的编程语言,你应该为你的数据使用对象,这个问题会简单得多。 –

+0

你应该考虑更多的功能,并研究lambda表达式。所有这些标准完全适合java.util.function包中的接口。 – duffymo

+0

以属于该语言的方式解决问题。因此,创建一个包含所需结构的类,而不是使用数组和地图。 –

回答

0

在Java中,您将创建一个Person类来存储与某人相关的数据,而不是将这些数据错误地保存在不同的数据结构中。那么,可能有一些外部约束让你做到了,即使Java不是那样使用的。我的建议是,创建一个类,并持有该类型的列表或地图:

public class Person { 
    private String name; 
    private int age; 
    private double weight; 

    public Person(String name, int age, double weight) { 
     this.name = name; 
     this.age = age; 
     this.weight = weight; 
    } 

    public String getName() { 
     return this.name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public int getAge() { 
     return this.age; 
    } 

    public void setAge(int age) { 
     this.age = age; 
    } 

    public double getWeight() { 
     return this.weight; 
    } 

    public void setWeight(double weight) { 
     this.weight = weight; 
    } 

    @Override 
    public String toString() { 
     String s = String.format("Person %s is %d years old and weighs %f lbs", name, String.valueOf(age), String.valueOf(double)); 
     return s; 
    } 

然后创建一个单一的List<Person>,添加一些Person S和打印出像

List<Person> persons = new ArrayList<Person>(); 
persons.add(new Person("Bob", 23, 160); 
persons.add(new Person("Rob", 20, 120); 
for (Person p : persons) { 
    System.out.println(p.toString()); 
} 
相关问题