Converting ArrayList to HashMap, however, selecting choice objects with different variable classes within ArrayList

all.k19 :

This is a project I am working on for my intro to java class. My professor has already laid out the base code, and the point of the project is to work with HashMaps and ArrayLists in combination with arithmetic. Everything here is done by my professor so far except:

HashMap<String, Integer> typeAttack = new HashMap<String, Integer>();

I am also provided with a .csv file containing various statistics of a whole list of pokemon. Out of the objects that my professor has already passed into the ArrayList "pokemonList," I only need to consider the "type" and "attack" variable, as I need to figure out which type of pokemon in the whole .csv file averages to have the highest attack level.

int attack = Integer.parseInt(split[1]);

String type = split[5];

My question is very simple. How can I convert only a portion of the ArrayList, specifically the "attack" and "type" variables into my HashMap?

import java.util.*;
import java.io.*;

public class Project6 {

    public static void main(String[] args) throws IOException {
        ArrayList<Pokemon> pokemonList = collectPokemon(args[0]);


   HashMap<String, Integer> typeAttack = new HashMap<String, Integer>();


    }

    // Don't modify this method. If you get errors here, don't forget to add the filename
    // as a command line argument.
    public static ArrayList<Pokemon> collectPokemon(String filename) throws IOException {
        BufferedReader file = new BufferedReader(new FileReader(new File(filename)));
        ArrayList<Pokemon> pokemonList = new ArrayList<Pokemon>();
        file.readLine();
        while(file.ready()) {
            String line = file.readLine();
            String[] split = line.split(",");
            String name = split[0];
            int attack = Integer.parseInt(split[1]);
            int defense = Integer.parseInt(split[2]);
            double height = Double.parseDouble(split[3]);
            double weight = Double.parseDouble(split[6]);
            String type = split[5];
            Pokemon current = new Pokemon(name, attack, defense, height, weight, type);
            pokemonList.add(current);
        }
        return pokemonList;
    }
}

POKEMON CLASS

import java.util.*;

public class Pokemon {

    private String name;
    private int attack;
    private int defense;
    private double height;
    private double weight;
    private String type;

    public Pokemon(String inName, int inAttack, int inDefense, double inHeight, double inWeight, String inType) {
        name = inName;
        attack = inAttack;
        defense = inDefense;
        height = inHeight;
        weight = inWeight;
        type = inType;
    }

    public String getName() {
        return name;
    }

    public int getAttack() {
        return attack;
    }

    public int getDefense() {
        return defense;
    }

    public double getHeight() {
        return height;
    }

    public double getWeight() {
        return weight;
    }

    public String getType() {
        return type;
    }

    public String toString() {
        return "Pokemon: '" + name + "' Atk: " + attack + " Def: " + defense + " Ht: " + height + "m Wt: " + weight + "Kg Type: " + type;
    }
}
Jakub Licznerski :

You could try with a simple for each loop:

// Note the Map type change to Double!
HashMap<String, Double> typeToAvgAttack = new HashMap<String, Double>();

// Intermediate map to store list of all attack values per type
HashMap<String, List<Integer>> typeToAttack = new HashMap<String, List<Integer>>();

for (Pokemon pokemon: pokemonList) {
    String type = pokemon.getType();
    int attack = pokemon.getAttack();

    // the map is empty at start, we need to check for the keys (pokemon type) existance
    List<Integer> attackValues = typeToAttack.get(type); 
    if (attackValues == null) {
        typeToAttack.put(type, attackValues = new ArrayList());
    }
    attackValues.add(attack);
}

// Iterate over map keys to calculate the average
for (String type : typeToAttack.keySet()) {
    List<Integer> attackValues = typeToAttack.get(type);
    double average = calculateAverage(attackValues);
    typeToAvgAttack.put(type, average);
}

The helper function, copied from here:

public static double calculateAverage(List <Integer> values) {
    double sum = 0d;
    if(!values.isEmpty()) {
        for (Integer value: values) {
            sum += value;
        }
        return sum / values.size();
    }
    return sum;
}

Be aware though that this approach is neither optimal nor elegant. I'd prefer to use Stream API, but that may not be best suited for your current proficiency.

EDIT: I've adjusted the code not to use Java 8 methods.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Converting HashMap to Sorted ArrayList

分類Dev

Thread-safe HashMap of Objects with Nested ArrayList

分類Dev

How can i use a for each loop to print an Arraylist of different objects of different classes

分類Dev

How to add different class objects into ArrayList

分類Dev

Objects to ArrayList

分類Dev

Converting JSONarray to ArrayList

分類Dev

Converting ArrayList<String> to int[]

分類Dev

Converting arraylist to JSON

分類Dev

How to add HashMap to ArrayList

分類Dev

Jackson: Convert JSON to object: ArrayList of objects with arraylist of objects with arraylist of objects

分類Dev

Inserting different arrays in a ArrayList

分類Dev

Decimal to Binary within an ArrayList java

分類Dev

Java error when converting String in ArrayList to int

分類Dev

Reading Strings from a file to an ArrayList then converting to an Array

分類Dev

LinkedHashMapとHashMap!= LinkedListとArrayList

分類Dev

ArrayListを更新するHashMap

分類Dev

Java HashMap:arraylistへの追加

分類Dev

How to set ArrayList<HashMap<String, String>> in AlertDialog?

分類Dev

HashMapとArrayListの順序

分類Dev

ArrayListはHashMapで空です

分類Dev

How To Sort ArrayList in Different List

分類Dev

ArrayList <HashMap <String、String >>を別のArrayList <HashMap <String、String >>に追加します

分類Dev

HashMap の HashMap を ArrayList の ArrayList に変換する

分類Dev

ArrayList IndexOutOfBoundsException despite adding within the capacity of the list

分類Dev

Finding index of recurring objects in an ArrayList in Java

分類Dev

How to get objects from generic ArrayList with Iterators?

分類Dev

How to have an arraylist of general objects as argument?

分類Dev

get list of unique objects from an arraylist in java

分類Dev

Finding same objects assigned to a string in an ArrayList

Related 関連記事

  1. 1

    Converting HashMap to Sorted ArrayList

  2. 2

    Thread-safe HashMap of Objects with Nested ArrayList

  3. 3

    How can i use a for each loop to print an Arraylist of different objects of different classes

  4. 4

    How to add different class objects into ArrayList

  5. 5

    Objects to ArrayList

  6. 6

    Converting JSONarray to ArrayList

  7. 7

    Converting ArrayList<String> to int[]

  8. 8

    Converting arraylist to JSON

  9. 9

    How to add HashMap to ArrayList

  10. 10

    Jackson: Convert JSON to object: ArrayList of objects with arraylist of objects with arraylist of objects

  11. 11

    Inserting different arrays in a ArrayList

  12. 12

    Decimal to Binary within an ArrayList java

  13. 13

    Java error when converting String in ArrayList to int

  14. 14

    Reading Strings from a file to an ArrayList then converting to an Array

  15. 15

    LinkedHashMapとHashMap!= LinkedListとArrayList

  16. 16

    ArrayListを更新するHashMap

  17. 17

    Java HashMap:arraylistへの追加

  18. 18

    How to set ArrayList<HashMap<String, String>> in AlertDialog?

  19. 19

    HashMapとArrayListの順序

  20. 20

    ArrayListはHashMapで空です

  21. 21

    How To Sort ArrayList in Different List

  22. 22

    ArrayList <HashMap <String、String >>を別のArrayList <HashMap <String、String >>に追加します

  23. 23

    HashMap の HashMap を ArrayList の ArrayList に変換する

  24. 24

    ArrayList IndexOutOfBoundsException despite adding within the capacity of the list

  25. 25

    Finding index of recurring objects in an ArrayList in Java

  26. 26

    How to get objects from generic ArrayList with Iterators?

  27. 27

    How to have an arraylist of general objects as argument?

  28. 28

    get list of unique objects from an arraylist in java

  29. 29

    Finding same objects assigned to a string in an ArrayList

ホットタグ

アーカイブ