如何让列表中的随机数组在 Java 中相互匹配?

How do I get shuffled arrays in a list to match up with each other in Java?

我是编码新手,我想知道如何编写此程序以使数组匹配。 (苹果和 1 号匹配,香蕉和 2 号匹配,芒果和 3 号匹配)我用过 assert fruits.size() == numbers.size(); 但它仍然不起作用,有什么办法可以解决这个问题吗?

package example;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.JOptionPane;

public class Example {
    
    public static void main(String[] args) {
final StringBuilder generator = new StringBuilder();
final List<String> fruits = Arrays.asList("apples", "bananas", "mangos");
final List<Integer> numbers = Arrays.asList(1, 2, 3);

Collections.shuffle(fruits);
Collections.shuffle(numbers);

assert fruits.size() == numbers.size();

for (int i = 0; i < fruits.size(); i++) {
int a = i+1;
    final String name = JOptionPane.showInputDialog(null, "Enter person " + a + "'s name");

    generator.append(name)
        .append(" likes ")
        .append(fruits.get(i))
        .append(" and the number ")
        .append(numbers.get(i))
        .append("\n");
}

JOptionPane.showMessageDialog(null, generator);
    }
}

我希望输出为:

Alex 喜欢芒果和数字 3

约翰喜欢苹果和数字 1

简喜欢香蕉和数字 2

而不是:

Alex 喜欢芒果和数字 1

约翰喜欢香蕉和数字 3

简喜欢苹果和数字 2

我会说水果和数字在概念上属于同一个对象(一对由数字+水果名称组成)。

您应该将这些对组成一个数组(例如使用 AbstractMap.SimpleEntry<String, Integer>,这基本上是一对以水果名称为键,数字为值的对),然后将其打乱。

然后你可以用getKey()检索名字和用getValue()

检索号码
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.AbstractMap;
import javax.swing.JOptionPane;

public class Example {

    public static void main(String[] args) {
        final StringBuilder generator = new StringBuilder();

        final List<AbstractMap.SimpleEntry<String, Integer>> fruits = Arrays.asList(
                new AbstractMap.SimpleEntry("apples", 1),
                new AbstractMap.SimpleEntry("bananas", 2),
                new AbstractMap.SimpleEntry("mangos", 3)
        );

        Collections.shuffle(fruits);

        for (int i = 0; i < fruits.size(); i++) {
            final String name = JOptionPane.showInputDialog(null, "Enter person " + (i + 1) + "'s name");

            generator.append(name)
                    .append(" likes ")
                    .append(fruits.get(i).getKey())
                    .append(" and the number ")
                    .append(fruits.get(i).getValue())
                    .append("\n");
        }

        JOptionPane.showMessageDialog(null, generator);
    }
}

示例输出:

假设您有两个列表:

final List<String> fruits = Arrays.asList("apples", "bananas", "mangos");
final List<Integer> numbers = Arrays.asList(1, 2, 3);

你可以这样做:

Map<Integer, String> numberToFruit = new HashMap<>();

for (int i = 0; i < fruits.size(); i++) {
    numberToFruit.put(numbers.get(i), fruits.get(i));
}

Collections.shuffle(numbers);

List<String> newFruits = numbers.stream()
        .map(numberToFruit::get)
        .collect(Collectors.toList());

System.out.println(newFruits);
System.out.println(numbers);

输出:

[apples, mangos, bananas]
[1, 3, 2]