java - 如何访问 Guava 多重映射的所有值?

标签 java key-value multimap

我正在制作一个“世界模拟器”程序。但我不知道如何访问每个键的所有值。在我的世界类中,我尝试执行方法“drawWorld”,但是每当两个或多个生物体位于同一个池中时,我的程序就看不到这一点。示例输出:

  0  [F2][F4][F8]  4    5    6    7    8  [F1]
  10    11    12    13  [F5]  15    16    17    18    19  
[F7]  21    22    23    24    25    26    27    28    29  
  30  [F6]  32    33    34    35  [F3]  37    38    39  
  40    41    42    43    44    45    46    47    48    49  
  50    51    52    53    54    55    56    57    58    59  
  60    61    62    63    64    65    66    67    68    69  
  70    71    72    73    74    75    76    77    78    79  
  80    81    82    83    84    85    86    87    88    89  
  90    91    92    93    94    95    96    97    98    99  

其中每个 F(F1、F2 等)都是 Fox 对象,在这个特定示例中,F2、F4 和 F8 位于同一池(在世界地图中),但程序将其显示为位于不同池中(而不是 1 [ F2][F4][F8] 4 5 应为 1 [F2,F4,F8] 3 4 )。你能告诉我我哪里出错了吗?我确信我的逻辑是: world.checkIfPoolHasOneOrMultipleOrganisms 很糟糕,问题是我不确定出了什么问题

import Obiektowe.WorldSimulator.Animal.Fox;

public class WorldSimulatorDemo {

    public static void main(String[] args) {
        World world = new World();
        world.drawWorld();
        Organism fox = new Fox(world, 10, 10);
        Organism foxxy = new Fox(world, 10, 10);
        Organism foxter = new Fox(world, 10, 10);
        Organism foxtser = new Fox(world, 10, 10);
        Organism foxtedr = new Fox(world, 10, 10);
        Organism foxterd = new Fox(world, 10, 10);
        Organism foxtera = new Fox(world, 10, 10);
        Organism foxtesr = new Fox(world, 10, 10);

        for (int i = 0; i < 2; i++) {
            world.makeTurn();
            world.drawWorld();
        }
    }
}
package Obiektowe.WorldSimulator;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import lombok.Data;

import java.util.*;

@Data
public class World {
    List<Organism> organisms;
    Multimap<Integer, Organism> worldMap;
    private static boolean wasPopulatedWithEmptyEntries = false;

    public World() {
        this.organisms = new ArrayList<>();
        this.worldMap = ArrayListMultimap.create();
        populateMapWithEmptyEntries();
    }

    public void addOrganismToWorldMap(Organism o) {
        Random random = new Random();
        int randomNumber = random.nextInt(10);
        worldMap.put(randomNumber, o);
    }

    public void makeTurn() {
        System.out.println("\n ***** NEW ROUND ***** \n");
        for (Organism o : organisms) {
            o.action();
        }
    }

    public boolean defineIfOrganismsOnTheSamePoolAreSameType(int pool) {
        return false;
    }

    protected void drawWorld() {
        int counter = 0;
        for (Map.Entry<Integer, Organism> entry : worldMap.entries()) {
            if (counter > 99
            ) {
                break;
            }
            if (counter % 10 == 0) {
                System.out.println();
            }
            if (entry.getValue() == null) {
                System.out.print("  " + counter + "  ");
            } else {
                // System.out.print(entry.getValue() + ",");
                checkIfPoolHasOneOrMultipleOrganisms(entry.getValue());
            }
            counter++;
        }
    }

    private void checkIfPoolHasOneOrMultipleOrganisms(Organism entryValue) {
        List<String> organismList = new LinkedList<>();
        StringBuilder stringBuilder = new StringBuilder();
        String formatedValue;
        organismList.add(entryValue.toString());
        if (organismList.size() == 1) {
            System.out.print(organismList);
        }
        if (organismList.size() == 2) {
            for (String string : organismList) {
                stringBuilder
                        .append(string)
                        .append(",");
            }
            formatedValue = stringBuilder.toString();
            System.out.print(formatedValue);
        }
    }

    private void populateMapWithEmptyEntries() {
        for (int i = 0; i < 100; i++) {
            worldMap.put(i, null);
        }
    }
}

import lombok.Data;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Data
public abstract class Organism {

    protected World world;
    protected int strength;
    protected int speed;

    public Organism(final World world, final int strength, final int speed) {
        this.world = world;
        this.strength = strength;
        this.speed = speed;
        getWorld().getOrganisms().add(this);
    }


    protected abstract void action();

    protected abstract void collision();

    protected abstract void draw();


}
package Obiektowe.WorldSimulator.Animal;

import Obiektowe.WorldSimulator.Organism;
import Obiektowe.WorldSimulator.World;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;

import java.util.Random;

@Getter
@Setter
@Data
public abstract class Animal extends Organism {


    public Animal(final World world, final int strength, final int speed) {
        super(world, strength, speed);
        // this.coordinates = world.worldMap[worldCoordinateX][worldCoordinateY];
    }

    @Override
    protected void action() {
    }

    @Override
    protected abstract void collision();

    protected abstract void move();

    @Override
    protected abstract void draw();

    @Override
    public String toString() {
        return "Animal";
    }
}
package Obiektowe.WorldSimulator.Animal;

import Obiektowe.WorldSimulator.Organism;
import Obiektowe.WorldSimulator.World;
import lombok.Data;

import java.util.Map;
import java.util.Random;

@Data
public class Fox extends Animal {
    protected int id;
    protected static int idCcounter;
    private boolean isAdded = false;

    public Fox(final World world, final int strength, final int speed) {
        super(world, strength, speed);
        idCcounter++;
        id = idCcounter;
    }

    @Override
    protected void action() {
        checkIfOrganismWasAddedToWorldMap();
        move();
    }

    @Override
    protected void collision() {

    }


    @Override
    protected void move() {
        int currentOrganismPosition = 0;
        int newOrganismPosition;
        for (Map.Entry<Integer, Organism> entry : getWorld().getWorldMap().entries()) {
            if (entry.getValue() != null && entry.getValue().equals(this)) {
                currentOrganismPosition = entry.getKey();
            }
        }
        newOrganismPosition = randomlyChangePosition(currentOrganismPosition);
        getWorld().getWorldMap().remove(currentOrganismPosition, this);
        getWorld().getWorldMap().put(newOrganismPosition, this);
    }

    private int randomlyChangePosition(int currentOrganismPosition) {
        final int NUMBER_TO_MOVE_LEFT_BY_1 = -1;
        final int NUMBER_TO_MOVE_RIGHT_BY_1 = 1;
        final int NUMBER_TO_MOVE_UP_BY_1 = -10;
        final int NUMBER_TO_MOVE_DOWN_BY_1 = 10;
        final int MIN_WORLDMAP_POSITION = 0;
        final int MAX_WORLDMAP_POSITION = 99;
        Random random = new Random();
        int randomNumber = random.nextInt(4) + 1;
        int newPosition;

        switch (randomNumber) {
            case 1:
                //Move left
                newPosition = NUMBER_TO_MOVE_LEFT_BY_1;
                break;
            case 2:
                //Move right
                newPosition = NUMBER_TO_MOVE_RIGHT_BY_1;
                break;
            case 3:
                //Move up
                newPosition = NUMBER_TO_MOVE_UP_BY_1;
                break;
            case 4:
                //Move down
                newPosition = NUMBER_TO_MOVE_DOWN_BY_1;
                break;
            default:
                newPosition = 0;
        }
        if (currentOrganismPosition + newPosition >= MIN_WORLDMAP_POSITION &&
                currentOrganismPosition + newPosition <= MAX_WORLDMAP_POSITION) {
            return currentOrganismPosition + newPosition;
        } else {
            return 0;
        }
    }

    @Override
    protected void draw() {

    }

    protected void checkIfOrganismWasAddedToWorldMap() {
        if (!isAdded) {
            getWorld().addOrganismToWorldMap(this);
            isAdded = true;
        }
    }

    @Override
    public String toString() {
        return "F" + id;
    }

}

最佳答案

我将方法更改为:

  protected void drawWorld() {
        int counter = 0;
        for (Map.Entry<Integer, Collection<Organism>> entry : worldMap.asMap().entrySet()) {
            Collection<Organism> valuesForKey = entry.getValue();
            if (counter % 10 == 0) {
                System.out.println();
            }
            if (valuesForKey.size() == 1) {
                System.out.print("  " + counter + "  ");
            } else {
                printValuesWithoutNullEntry(valuesForKey);
            }
            counter++;
        }
    }

    private void printValuesWithoutNullEntry(Collection<Organism> organisms) {
        final int INDEX_WHERE_NULL_PHRASE_ENDS = 7;
        System.out.print("[" + organisms.toString().substring(INDEX_WHERE_NULL_PHRASE_ENDS));
    }

现在它可以工作了,现在我只需要找到一种不在空条目处显示空值的方法,它应该容易得多:)

关于java - 如何访问 Guava 多重映射的所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61351091/

相关文章:

C# Linq 结果 ToDictionary 帮助

c++ - Multimap 与运算符不匹配==

C++ 映射问题

Java - 只执行一次方法

java - 线程 "main"java.sql.SQLException : No value specified for parameter 1 中的异常

java - Foreach 键/值对问题

python - 是否可以查找某个数字下的字典值的键?

c++ - 如何在一段时间内从 multimap 中删除多个项目?

java - 框架中面板的固定尺寸

java - 当我调用事件时,onTouchEvent 的 ACTION_DOWN MotionEvent 中的代码抛出异常