如何组合数组和映射并对其执行某些操作?

时间:2017-10-06 17:04:57

标签: java

我有两个数组

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(....
        }
    }

我使用这些数组和地图来打印以下内容:
bob 30yr 160lbs
抢40升170磅

  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;
        }

如何开始创建这些方法?

1 个答案:

答案 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并打印出每个Person的数据,如

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());
}