2017-10-06 99 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()); 
} 
相關問題