user3511611
user3511611

Reputation: 43

Two ArrayList into a TreeMap

I've been searching StackOverflow for an answer regarding this issue.

Lets say I created two array lists,

arraylist1 holds Strings arraylist2 holds Integers.

NOTE - I've added things into both of these arraylists. The values at each of the indices are related to the other value.

Meaning. lets say index 1 of arraylist1 = "Name". Index 1 of arraylist2 = 3, they are related in that I want to put things into a TreeMap (for the purpose of sorting by key) so that the treemap puts in the value ("Name", 3).

My problem -

TreeMap<String, Integer> mymap = new TreeMap<String, Integer>();
for(String s : arraylist1) {
     for(Integer v : arraylist2) {
          mymap.put(s, v); 

The problem with this is if I added a bunch of random things for testing,

    arraylist1.add("h");
    arraylist1.add("i");
    arraylist1.add("e");
    arraylist2.add(1);
    arraylist2.add(3);
    arraylist2.add(2);

And I did the for loops, my result would come out to...

Key e Value: 2
Key h Value: 2
Key i Value: 2

Which solves the problem of sorting by key. However, the problem is that only the last value in the Integer arraylist, arraylist2, is being put into the TreeMap.

Upvotes: 0

Views: 971

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Well fark, I was typing this in your deleted question before you deleted it, but didn't finish til after you deleted it:

I'm not sure if I fully understand your question, but consider:

  • Creating a Game class that is in charge of the logic of the game.
  • Creating Player objects that interact with the Game.
  • When a Player wants to move, he calls Game's move(Piece piece, Position position) method, but with parameters.
  • Have this method return a boolean, true if the move is valid and false if not...

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272297

Don't you want to iterate through both lists at the same time ?

for (int i = 0; i < list.size(); i++) {
   map.put(list1.get(i), list2.get(i));
}

As it currently stands, you're iterating over your second map for each key, and inserting the second list's values. Since a map only holds one value per key, your map results in the final value in your second list for each key.

As an aside, if these 2 values are intrinsically linked, perhaps create (or use an existing) Pair object to store these from the outset. The problem with using a standard map is that you can only store one value per key. e.g. you can't store (A,B) and (A,C)

Upvotes: 4

Related Questions