0

I have this problem that I don't know how to approach. I have two array list, one that contains String and the other one containing integers, like this:

 *  Utah           5
 *  Nevada         6
 *  California    12
 *  Oregon        8
 *  Utah          9
 *  California   10
 *  Nevada        4
 *  Nevada        4
 *  Oregon       17
 *  California    6

and i need to produce a result like this in array lists: Utah [5, 9] Nevada [6, 4, 4] California [12, 10, 6].

I honestly don't know how to approach this and I'm looking an advice on how to do it.

I was suggested to use arraylist Of arraylist and this is what I have so far.

    int i=0;
        ArrayList<ArrayList<Integer>> values  = new ArrayList<ArrayList<Integer>>();

        while (i<categories.size())
        {
            String cat=categories.get(i);
            i++;
            for (int r = 0; r < column1.size();r++) {
                if(column1.get(r)==cat)
                {
                    int value = column2.get(r);
                    ArrayList<Integer> val=new ArrayList<Integer>();
                    val.add(value);
                    values.add(val);
                }
        }

Column1=states list, column2=the integers list and categories= categories list.

My problem now is that the for loop seems to just be adding the same array over and over until the while loop is done. Any suggestions?

4
  • 2
    Map<String, List<Integer>> ? Commented Oct 7, 2014 at 3:55
  • Why not create 2 more ArrayList, one that holds the names but only one instance of each name, and then another that would go through the first (not the third) arraylist and if the value matches a value (need a loop that goes through them all) from the 3rd arraylist, then append that value to the 4th arraylist, and repeat. I think that would work. Is this for a homework assignment? Commented Oct 7, 2014 at 3:58
  • yeah it is for homework, but i guess what i dont get is how to know what values are in front of the categories (utah, nevada, california) since I cant really see them, I just though maybe just by the index number? Commented Oct 7, 2014 at 4:16
  • 3
    The Guava library provides a Multimap implementation, which lets you easily and clearly associate keys with multiple values. As a homework assignment using an external library may not be the point of the exercise, but the "right" way to address this type of problem is with a Multimap. Commented Oct 7, 2014 at 4:34

3 Answers 3

5

You can solve the problem by using the following approach:

List<String> states = Arrays.asList(
        "Utah", "Nevada", "California", "Oregon", "Utah",
        "California", "Nevada", "Nevada", "Oregon", "California"
    );

List<Integer> values = Arrays.asList(5, 6, 12, 8, 9, 10, 4, 4, 17, 6);


Map<String, List<Integer>> resultMap =HashMap<String, Arraylist<>>();

for(int i = 0; i < states.size(); i++) 
    {
           if( resultMap.get(states.get(i))!=null){
              resultMap.get(states.get(i)).add(values.get(i));
           }else{
            List<Integer> valuelist = new ArrayList<>();
             valuelist.add(values.get(i));
             resultMap.put(states.get(i),valuelist);
          }
    }  

resultMap contains your required answer.

Sign up to request clarification or add additional context in comments.

2 Comments

How did this get 6 upvotes? It doesn't even compile.
this is an approach to problem...its not 100% syntax error free @JeffreyBosboom..
2

This seems like a homework-level question, and it's relatively straightforward to solve using lists of Integer in a Map keyed by String. I'm answering in order to play with demonstrate some of the newer Java 8 features:

    List<String> states = Arrays.asList(
        "Utah", "Nevada", "California", "Oregon", "Utah",
        "California", "Nevada", "Nevada", "Oregon", "California"
    );
    List<Integer> values = Arrays.asList(
        5,  6, 12,  8, 9,
        10, 4,  4, 17, 6
    );
    assert states.size() == values.size();

    Map<String, List<Integer>> collated = new LinkedHashMap<>();
    for (int i = 0, len = states.size(); i < len; i++) {
        String state = states.get(i);
        Integer value = values.get(i);
        collated.computeIfAbsent(state, x -> new ArrayList<>()).add(value);
    }
    collated.forEach( (k,v) -> System.out.printf("%s %s%n", k, v) );

Output:

Utah [5, 9]
Nevada [6, 4, 4]
California [12, 10, 6]
Oregon [8, 17]

2 Comments

thanks man, I'm trying to understand how this works but honestly there are several things I'm not familiar with at all. Like the map keyded. I'll keep trying to understand it.
Start by doing a Google search for the class names that are unfamiliar to you. Read the Javadoc for those API classes and their methods, if you're still confused, read them again.
1

Here's another way to compute this with Java 8 features, but with streams this time. (scaffolding from @William Price's answer)

List<String> states = Arrays.asList(
    "Utah", "Nevada", "California", "Oregon", "Utah",
    "California", "Nevada", "Nevada", "Oregon", "California"
);
List<Integer> values = Arrays.asList(5, 6, 12, 8, 9, 10, 4, 4, 17, 6);
assert states.size() == values.size();

Map<String, List<Integer>> collated = IntStream.range(0, states.size()).boxed().collect(
    Collectors.groupingBy(states::get, LinkedHashMap::new,
        Collectors.mapping(values::get, Collectors.toList())));

collated.forEach((k,v) -> System.out.printf("%s %s%n", k, v));

Working with multiple input sources can be awkward in streams, but using a stream of indices is perfect for this "corresponding-list" case. groupingBy classifies the indices by their value in the states list, mapping maps the indices to their value in the values list, and toList, well, collects them into a list. Using LinkedHashMap preserves the order of insertion.

1 Comment

+1 Good variation demonstrating streams and collectors. Probably harder for a casual student to grasp at first, but greater potential for that "a-ha!" lightbulb moment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.