This discussion is archived
3 Replies Latest reply: Apr 15, 2013 2:34 PM by 1003073 RSS

Accessing map values through a List

1003073 Newbie
Currently Being Moderated
I am trying to create a method in BlueJ which needs the values from a Map to be copied into a List so I can use the List methods min() and max(). Here is the method I have created so far:

public String findNamesInPageRange()
{
int minOfRange = Integer.parseInt(OUDialog.request("Input number for start of range"));
int maxOfRange = Integer.parseInt(OUDialog.request("Input number for end of range"));
String foundIt = null;

for(String eachKey : bookIndex.keySet())
{
List<Integer> pageList = new ArrayList<>(); //Cannot access values from a map using this List
if((minOfRange >= Collections.min(pageList)) && (maxOfRange <= Collections.max(pageList)))

{
foundIt = eachKey;
}
}
return foundIt;
}

As can be seen there is a comment showing where my problem lies.

The Map is coded as Map<String, Set<Integer>> bookIndex = new TreeMap<>();

Ive tried using bookIndex.values() as the argument of the List but I get an incompatible type error

So, how can this problem I am having be resolved?
  • 1. Re: Accessing map values through a List
    thomas.behr Newbie
    Currently Being Moderated
    First, use {code}-tags when posting code.




    1000070 wrote:
    Ive tried using bookIndex.values() as the argument of the List but I get an incompatible type error
    Second, your map stores sets of integers as values. However, your list is declared to store integers. Obviously, a set of integers is something different than a single integer.

    That said, I would like to know why you think it's necessary to copy your values to a list first before using Collections.min/Collections.max? After all, both methods work on java.util.Collection and your sets are collections.
  • 2. Re: Accessing map values through a List
    Kayaman Guru
    Currently Being Moderated
    1000070 wrote:
    Ive tried using bookIndex.values() as the argument of the List but I get an incompatible type error
    And what does the error say? Java is very helpful with the errors, so it should tell the type it's expecting.

    But your problem comes from the fact that bookIndex.values() returns a Collection of Sets. You could go through all those sets and addAll() them to your ArrayList, but it sounds like using List is the wrong way to go here.

    If I were you, I'd rethink the logic. Maybe write it out in English and then figure out the most logical way to handle this.
  • 3. Re: Accessing map values through a List
    1003073 Newbie
    Currently Being Moderated
    Thank you everyone. I did not realize that min() and max() could be used for Sets

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points