最合适的“ 2D”表示形式,用于在Java中并排存储字符串和双精度值?

问题描述 投票:1回答:2

我正在寻找一种可以同时存储字符串和双精度数据以保持记录的数据类型。字符串是一些密码,而double是该密码的某个分数,这是在将密码插入数据结构后确定的。哪种数据类型最适合这种情况?

到目前为止,我一直在使用ArrayList,每位数据各使用一个,但是到了我需要按一部分进行排序的地步,而后勤对我来说并不是特别有吸引力。

例如:

private ArrayList<String> keys = ArrayList<String>();
private ArrayList<Double> scores = ArrayList<Double>();
// n and m determined at runtime

private void generateKeys(int m, int n) {
    for (int i = 0; i < m; i++) {
        keys.add(getRandomKey(n));
    }
}

private String getRandomKey(int n) {
    String key = "";
    String charValues = "abcdefghijklmnopqrstuvwxyz";
    int randIndex;
    for (int i = 0; i < n; i++) {
        randIndex = random.nextInt(26);
        key += charValues.charAt(randIndex);
    }
    return key;
}

private void generateScores() {
    for (int i = 0; i < size(keys); i++) {
        scores.add(findScore(keys.get(i)));
    }
}

private double findScore(String k) {
    // some function
}

示例数据将是:

    key     score
"fsuifshu", 0.950
"wowaflsa", 0.120
"woawfjff", 0.430
"fireplfd", 0.040
...

首先使用循环和随机字符生成器插入key,然后在已经插入每个score之后计算key。我确实希望能够移动它们(根据score排序)。

最终,我希望能够根据它们的分数对它们进行排序。因此,基于上述内容的预期输出将是:

"fsuifshu"
"woawfjff"
"wowaflsa"
"fireplfd"

例如,经过排序的ArrayList将包含该列表。

java arrays arraylist containers
2个回答
2
投票

您要使用java.util.Map。它存储键值对。

Map<String, Double> map = new HashMap<>();

map.put("foo", 1.0D);

0
投票

这是我会做的完整示例:

public static void main(String[] args) {
    List<PasswordAndScore> passwords = new ArrayList<>();

    int numberOfPasswords = 5;
    int lengthOfPassword = 5;

    Random rand = new Random();
    String chars = "abcdefghijklmnopqrstuvwxyz";

    for (int i = 0; i < numberOfPasswords; i++) {
        StringBuilder password = new StringBuilder();
        for (int j = 0; j < lengthOfPassword; j++) {
            password.append(chars.charAt(rand.nextInt(chars.length())));
        }
        passwords.add(new PasswordAndScore(password.toString()));
    }

    passwords.sort(Comparator.comparing(PasswordAndScore::getScore).reversed());

    System.out.println(passwords);
}

public static class PasswordAndScore {
    private final String password;
    private final double score;

    public PasswordAndScore(String password) {
        this.password = password;
        this.score = findScore(password);
    }

    public String getPassword() {
        return password;
    }

    public double getScore() {
        return score;
    }

    @Override public String toString() {
        return password + ": " + score;
    }
}


public static double findScore(String password) {
    // but different
    return password.chars().sum();
}
© www.soinside.com 2019 - 2024. All rights reserved.