Java: Combine 2 List <String[]> - java

I have two List of array string. I want to be able to create a New List (newList) by combining the 2 lists. But it must meet these 3 conditions:
1) Copy the contents of store_inventory into newList.
2) Then if the item names in store_inventory & new_acquisitions match, just add the two quantities together and change it in newList.
3) If new_acquisitions has a new item that does not exist in store_inventory, then add it to the newList.
The titles for the CSV list are: Item Name, Quantity, Cost, Price.
The List contains an string[] of item name, quantity, cost and price for each row.
CSVReader from = new CSVReader(new FileReader("/test/new_acquisitions.csv"));
List <String[]> acquisitions = from.readAll();
CSVReader to = new CSVReader(new FileReader("/test/store_inventory.csv"));
List <String[]> inventory = to.readAll();
List <String[]> newList;
Any code to get me started would be great! =]
this is what i have so far...
for (int i = 0; i < acquisitions.size(); i++) {
temp1 = acquisitions.get(i);
for (int j = 1; j < inventory.size(); j++) {
temp2 = inventory.get(j);
if (temp1[0].equals(temp2[0])) {
//if match found... do something?
//break out of loop
}
}
//if new item found... do something?
}

I would start by building the newList as a HashMap or TreeMap instead of a List. This makes it easy to search for the matching record. Furthermore, I would convert the String[] to a custom object (e.g. Record) that contains the name, quantity, cost and price field. This would take care of copying the information. The you could try something like this:
Map<String, Record> newMap = new TreeMap<String, Record>();
for(String[] ss : acquisitions) {
Record rec = Record.parse(ss); // For requirement (1)
newMap.put(rec.getName(), rec);
}
for(String[] ss : inventory) {
Record rec = Record.parse(ss); // For requirement (1)
if(newMap.containsKey(rec.getName())) {
// For requirement (2)
// The mergeWith method can then add quantities together
newMap.get(rec.getName()).mergeWith(rec);
} else {
// For requirement (3)
newMap.put(rec.getName(), rec);
}
}
edit
An extra advantage of having a Record object, is that it can be printed to screen much easier by implementing the toString function.
public class Record implements Comparable<Record> {
public static Record parse(String[] ss) {
// TODO: implement some basic parsing
}
private String name;
private int quantity;
private BigDecimal cost, price;
private Record() {}
public String getName() { return name; }
public int getQuantity() { return quantity; }
public BigDecimal getCost() { return cost; }
public BigDecimal getPrice() { return price; }
public int compareTo(Record other) {
return this.name.compareTo(other.name);
}
public String toString() {
return name;
}
}

Related

Remove duplicates from an arraylist with strings

I have an arraylist that looks like this:
public static ArrayList<ArrayList<String[]>> x = new ArrayList<>();
I store groups of 2 persons in a pair. For example:
[Person1, Person2]
[Person3, Person4]
The algorithm I use right now still makes duplicates, I've tried out hashmaps and iterating through them with for loop but they just give me back the original list.
This is the code:
package com.company;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
public class createGroups
{
public static ArrayList<ArrayList<String[]>> x = new ArrayList<>();
public static void main(String[] args){
//Define names
String[] names = {"Person1", "Person2", "Person3", "Person4"};
try
{
//Create combinations. In a try catch because of the saveFile method.
combination(names, 0, 2);
//Print all the pairs in the Arraylist x
printPairs();
} catch (IOException e)
{
e.printStackTrace();
}
}
static void combination(String[] data, int offset, int group_size) throws IOException
{
if(offset >= data.length)
{
//Create new Arraylist called foo
ArrayList<String[]> foo = new ArrayList<>();
//Create a pair of 2 (data.length = 4 / group_size = 2)
for(int i = 0; i < data.length / group_size; i++)
{
//Add the pair to foo.
foo.add(Arrays.copyOfRange(data, 2 * i, 2 * (i + 1)));
}
//Add foo to x
x.add(foo);
//saveFile(foo);
}
for(int i = offset; i < data.length; i++){
for(int j = i + 1; j < data.length; j++){
swap(data, offset, i);
swap(data, offset + 1, j);
combination(data, offset + group_size, group_size);
swap(data, offset + 1, j);
swap(data, offset, i);
}
}
}
public static void printPairs(){
//Print all pairs
for(ArrayList<String[]> q : x){
for(String[] s : q){
System.out.println(Arrays.toString(s));
}
System.out.println("\n");
}
}
private static void swap(String[] data, int a, int b){
//swap the data around.
String t = data[a];
data[a] = data[b];
data[b] = t;
}
}
The output right now is this:
Output
Every group of 4 names is a 'list' of pairs (Not really a list but that's what I call it)
And this is the desired output:
Desired output
But then you can see that the first and the last list of pairs are basically the same how do I change that in my combination method
The question:
How can I change my combination method so that it doesn't create duplicate groups.
And how can I make the list smaller (The desired output) when printing the created lists.
If I wasn't clear enough or if I didn't explain what I want very well, let me know. I'll try to make it clearer.
Create an object similar to this. It takes 4 strings (2 pairs). Puts the strings into array and sorts this array. That means any combination of strings you put in will be converted into one sorted combination, but the object internaly remembers which person is person1, person2, ...
private class TwoPairs {
private final String person1;
private final String person2;
private final String person3;
private final String person4;
private final String[] persons;
TwoPairs(String person1, String person2, String person3, String person4) {
this.person1 = person1;
this.person2 = person2;
this.person3 = person3;
this.person4 = person4;
persons = new String[4];
persons[0] = person1;
persons[1] = person2;
persons[2] = person3;
persons[3] = person4;
// if we sort array of persons it will convert
// any input combination into single (sorted) combination
Arrays.sort(persons); // sort on 4 objects should be fast
// hashCode and equals will be comparing this sorted array
// and ignore the actual order of inputs
}
// compute hashcode from sorted array
#Override
public int hashCode() {
return Arrays.hashCode(persons);
}
// objects with equal persons arrays are considered equal
#Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
TwoPairs other = (TwoPairs) obj;
if (!Arrays.equals(persons, other.persons)) return false;
return true;
}
// add methods which you might need
// getters for individual persons
// String getPerson1() { return person1; }
// or perhaps pairs of persons
// String[] getPair1() { return new String[] {person1, person2}; }
// add sensible toString method if you need it
}
Your ArrayList x will change like this
ArrayList<TwoPairs> x = new ArrayList<TwoPairs>();
before adding new TwoPairs object into x check if this list already contains this object.
if (!x.contains(twoPairsObject)) {
x.add(twoPairsObject);
}

Comparing Characters in ArrayLists?

I am trying to populate a RecyclerView with a custom adapter. This Adapter takes in a model that has setters and getters. This model contains three parameters: String username, int proPic, and int bckgImg. What i am trying to achieve is a RecyclerView with an alphabetical sorted list. I populate the model by using the following code:
private ArrayList<FriendsModel> friendsData = new ArrayList<>(0);
friendsData.add(new FriendModel("Erick", R.drawable.default_pro_pic, R.drawable bckgImg);
After i am done with populating 5 objects of the FriendModel, i then proceed to compare the characters found in the ArrayList:
for(char alph = 'A'; alph <= 'Z'; alph++){
List<String> friends = getFriends(alph);
if(friends.size() > 0){
//Populate the Sorted Alphabetical view
}
}
private List<String> getFriends(char alph) {
//Empty List used to populate when comparing existing model to alphabet
List<String> friends = new ArrayList<>();
//5 objects of FriendsData with three parameters
for (int i = 0; i < friendsData.size(); i++){
//If the first string parameter character at position 0 is equal to alph
if(friendsData.get(i).toString().charAt(0) == alph){
friends.add(friendsData.get(i).toString());
}
}
return friends;
}
I am not sure if i am doing this correctly, what is the adequate or correct way to compare the characters in an ArrayList based on its model?
Instead of using constructor to initialize the variables, always use the setter methods, such classes are also known as pojo(Plain old java objects) or VO(value objects).
Assuming your FriendModel class is like below..
public class FriendModel{
String username;
int proPic;
int bckgImg;
public FriendModel(){}
//redundant constructor, you can remove this since you are using setter methods now.
public FriendModel(String username, int proPic, int bckgImg){
this.username=username;
this.proPic=proPic;
this.bckgImg=bckgImg;
}
//you'll need the below getters and setters..
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getProPic() {
return proPic;
}
public void setProPic(int proPic) {
this.proPic = proPic;
}
public int getBckgImg() {
return bckgImg;
}
public void setBckgImg(int bckgImg) {
this.bckgImg = bckgImg;
}
}
And where ever you are doing the following,
for(char alph = 'A'; alph <= 'Z'; alph++){
List<String> friends = getFriends(alph);
if(friends.size() > 0){
//Populate the Sorted Alphabetical view
}
}
private List<String> getFriends(char alph) {
//Empty List used to populate when comparing existing model to alphabet
List<String> friends = new ArrayList<>();
//5 objects of FriendsData with three parameters
for (int i = 0; i < friendsData.size(); i++){
//If the first string parameter character at position 0 is equal to alph
String username=friendsData.get(i).getUsername(); //get the username
if(username.charAt(0) == alph){ //compare the username with charater in alph variable
friends.add(username); //add in another list
}
}
return friends;
}
Custom Comparator should help
Collections.sort(list, new Comparator<String>() {
#Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});
or if it's not work so us it
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
The proper way to sort the list with model is to define Comparator. For your current example you used use.
Collections.sort(friendsData, new Comparator<FriendsModel>() {
#Override
public int compare(FriendsModel obj1, FriendsModel obj2) {
return obj1.getUsername.compareTo(obj2.getUsername); //For Ascending order
//OR
return obj2.getUsername.compareTo(obj1.getUsername); //For Descending order
}
});
"compare" function compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

Adding quantities of Duplicate Strings

I've been tasked with sorting a list of categories. A shopping list, if you will. These categories are inputs from the user, items to be bought. After the string name of the category in question is input (using scanner of course) the user is then able to put in the quantity of that category (an integer), followed by the unit cost of that category(a double).
They are prompted to repeat this until the category they name is "end".
This is all fine and dandy, and I've already written code that takes all of this information and finds and prints out the largest cost item, the largest quantity item, and other info. What I need help with is my duplicate categories. For example, suppose the user puts in "cars" followed by an integer 3, followed by the number 24000.00. They then put in "refigerators" followed by 1, followed by 1300.00. And then the user puts in a duplicate of the first entry, which is "cars" followed by an integer 5, followed by the double 37000.00. How can I get my code revisit older entries, add the new quantity to the old one, and store that value without overriding the old stuff? I also need to find the largest average cost of the items in the list. I am new to HashMap, so I'm struggling with the code: // create an arrayList to store values
// create an arrayList to store values
ArrayList<String> listOne = new ArrayList<String>();
listOne.add("+ 1 item");
listOne.add("+ 1 item");
listOne.add("+ 1 item");
// create list two and store values
ArrayList<String> listTwo = new ArrayList<String>();
listTwo.add("+1 item");
listTwo.add("+1 item");
// put values into map
multiMap.put("some sort of user input detailing the name of the item", listOne);
multiMap.put("some other input detailing the name of the next item", listTwo);
// i need the user to input items until they type "end"
// Get a set of the entries
Set<Entry<String, ArrayList<String>>> setMap = multiMap.entrySet();
// time for an iterator
Iterator<Entry<String, ArrayList<String>>> iteratorMap = setMap.iterator();
System.out.println("\nHashMap with Multiple Values");
// display all the elements
while(iteratorMap.hasNext()) {
Map.Entry<String, ArrayList<String>> entry =
(Map.Entry<String, ArrayList<String>>) iteratorMap.next();
String key = entry.getKey();
List<String> values = entry.getValue();
System.out.println("Key = '" + key + "' has values: " + values);
}
// all that up there gives me this:
HashMap with Multiple Values
Key = 'some other input detailing the name of the next item' has values: [+1 item, +1 item]
Key = 'some sort of user input detailing the name of the item' has values: [+ 1 item, + 1 item, + 1 item]
but I haven't given the user a chance to input the number of items or the cost.... I'm lost.
Try this small bit of sample code, it includes a Main class and two dependency classes, StatsPrinter and ShoppingEntry
package com.company;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
String category;
String quantity;
String value;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
HashMap<String, List<ShoppingEntry>> shoppingList = new HashMap<String, List<ShoppingEntry>>();
while(true) {
System.out.print("Enter the category of your item: ");
category = bufferedReader.readLine();
if("end".equals(category)){
break;
}
System.out.print("Enter the quantity of your item: ");
quantity = bufferedReader.readLine();
System.out.print("Enter the value of your item: ");
value = bufferedReader.readLine();
if (shoppingList.containsKey(category)) {
shoppingList.get(category).add(new ShoppingEntry(Integer.parseInt(quantity), Double.parseDouble(value)));
}else{
shoppingList.put(category, new ArrayList<ShoppingEntry>());
shoppingList.get(category).add(new ShoppingEntry(Integer.parseInt(quantity), Double.parseDouble(value)));
}
}
StatsPrinter.printStatistics(shoppingList);
}
}
and the ShoppingEntry class
package com.company;
public class ShoppingEntry {
private int quantity;
private double price;
public ShoppingEntry(){
quantity = 0;
price = 0;
}
public ShoppingEntry(int quantity, double price){
this.quantity = quantity;
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
and finally the StatsPrinter class, which leverages the data structure of the HashMap of ShoppingEntry's to print the desired statistics
package com.company;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
public class StatsPrinter {
private static DecimalFormat format = new DecimalFormat("#.##");
public static void printStatistics(HashMap<String, List<ShoppingEntry>> shoppingList) {
printNuumberOfItems(shoppingList);
printLargestValue(shoppingList);
printLargestAverage(shoppingList);
}
private static void printNuumberOfItems(HashMap<String, List<ShoppingEntry>> shoppingList) {
System.out.println("There are " + shoppingList.keySet().size() + " items in your Shopping List");
}
private static void printLargestValue(HashMap<String, List<ShoppingEntry>> shoppingList) {
double currentLargestPrice = 0;
String largestPriceCategory = new String();
for(String keyValue : shoppingList.keySet()) {
for(ShoppingEntry entry : shoppingList.get(keyValue)) {
if (entry.getPrice() > currentLargestPrice) {
currentLargestPrice = entry.getPrice();
largestPriceCategory = keyValue;
}
}
}
System.out.println(largestPriceCategory + " has the largest value of: " + format.format(currentLargestPrice));
}
private static void printLargestAverage(HashMap<String, List<ShoppingEntry>> shoppingList) {
double currentLargestAverage = 0;
String largestAverageCategory = new String();
double totalCost = 0;
int numberOfItems = 0;
for(String keyValue : shoppingList.keySet()) {
for(ShoppingEntry entry : shoppingList.get(keyValue)) {
totalCost += entry.getPrice();
numberOfItems += entry.getQuantity();
}
if((totalCost / numberOfItems) > currentLargestAverage) {
currentLargestAverage = totalCost / numberOfItems;
largestAverageCategory = keyValue;
}
}
System.out.println(largestAverageCategory + " has the largest average value of: " + format.format(currentLargestAverage));
}
}
Instead of manipulating three separate values, create a class called Item. Implement the Comparable interface such that two Items are equal if they share a common name. See the Javadoc for Comparable for instructions on defining the interface.
public class Item implements Comparable {
[...]
}
Create a list of items.
List<Item> shoppingList;
When you want to add an item to the list, check if the list already contains it first.
// If it's already in the list, add their quantities together
if (shoppingList.contains(newItem))
shoppingList.get(newItem).quantity += newItem.quantity
// Otherwise, add it to the list
else
shoppingList.add(newItem);

How to add items to arraylist and modify a feature

I am trying to add items to my array list with an action listener on a pop up window. You can see the action listener here. The problem that I am now having is I do not know how to add the inputs to my array list. Part of this problem is that I need to set my item number to 1 higher than the highest in my list. My array list is named as such:
private static ArrayList<InventoryItem> inventory = new ArrayList<>();
and the class for InventoryItem looks like this:
public class InventoryItem { //Delcare variables below
DecimalFormat formatted = new DecimalFormat("#,###.00");//set up decimal format for displaying 12.34 type values
String itemName;
int itemNumber;
public String getItemName() {
return itemName;
}
public int getItemNumber(){
return itemNumber;
}
int inStock;
double unitPrice;
double value;
double restockingFee;
double inventoryValue;
public InventoryItem(String itemName, int itemNumber, int inStock, double unitPrice) { //declare variables for this class
this.itemName = itemName;
this.itemNumber = itemNumber;
this.inStock = inStock;
this.unitPrice = unitPrice;
stockValue(); //call stock value
}
}
So my question is two parts. The first is how do I get my itemNumber to increment to 1 higher than the highest? Do I simply do a bubble sort to find the highest? And the second part is how do I get it to add all items, including this incremented itemNumber, into my original arraylist?
Note
If needed I can paste my code in it's entirety on pastebin as it is somewhat large.
EDIT: Per #Prabhakaran I have added some code and I am almost there. I have almost gotten this to work, however when I start to look through my list I do not see the added feature so how can I be sure that I am actually adding it?
String newItemName = String.valueOf(xField);
String text1 = yField.getText();
String newInventoryAmount = String.valueOf(text1);
int newNumber = Integer.parseInt(newInventoryAmount);
String text2 = zField.getText();
String newUnitPrice = String.valueOf(text2);
double newPrice = Double.parseDouble(newUnitPrice);
for (int i = 0; i >= inventory.size(); i++) {
inventory.get(inventory.size() ).getItemNumber();
int newItemNumber;
newItemNumber = i + 1;
InventoryItem item = new InventoryItem(newItemName, newItemNumber, newNumber, newPrice);
inventory.add(item);
What am I missing here? Shouldn't this simply add an item to my arraylist? I know it must be something really easy, I just can't seem to figure it out.
Here is my sort by ItemName:
static ArrayList sortInventory(ArrayList<InventoryItem> unsorted) {
ArrayList<InventoryItem> sorted = new ArrayList<>(); //create new array list to sort
InventoryItem alpha = null;
int lowestIndex = **-1**;
while (unsorted.size() > 0) { //while my unsorted array is less than 0 do the following
for (int i = 0; i < unsorted.size(); i++) { //increment through
if (alpha == null) {
alpha = unsorted.get(i); //get the next line in the inventoryItem array
lowestIndex = i;
} else if (unsorted.get(i).itemName.compareToIgnoreCase(alpha.itemName) < 0) { //compare items to determine which has a higher value
alpha = unsorted.get(i);
lowestIndex = i;
}
}
sorted.add(alpha); //reset the index so it will loop until there are no more items in the unsorted array
unsorted.remove(lowestIndex);
alpha = null;
lowestIndex = **0**;
}
return sorted; //return the sorted arraylist
}
EDIT: Corrected the lowestIndex and it goes good as gold.
Do like this
private static ArrayList<InventoryItem> inventory = new ArrayList<>();
String newItemName = String.valueOf(xField);
String newInventoryNumber = String.valueOf(yField);
int newNumber = Integer.parseInt(newInventoryNumber);
String newUnitPrice = String.valueOf(zField);
double newPrice = Double.parseDouble(newUnitPrice);
InventoryItem item =new InventoryItem(newItemName , newInventoryNumber , newNumber , newUnitPrice ) ;
inventory.add(item);
update
class SimpleComparator implements Comparator<InventoryItem> {
#Override
public int compare(InventoryItem o1, InventoryItem o2) {
return new Integer(o1.getItemNumber()).compareTo(o2.getItemNumber());
}
}
//Sorting based on the itemNumber.
Collections.sort(inventory,new SimpleComparator());
int newItemNumber = inventory.get(inventory.size() - 1).getItemNumber();
newItemNumber ++;
You could create your own ArrayList with Observer support:
public class InventoryItemArrayList extends ArrayList {
private static final long serialVersionUID = 4550719458611714650L;
private List listeners = new ArrayList();
public void addInventoryItemAddedListener(InventoryItemAddedListener listener) {
this.listeners.add(listener);
}
#Override
public boolean add(InventoryItem e) {
boolean add = super.add(e);
fireInventoryItemAdded(e);
return add;
}
private void fireInventoryItemAdded(InventoryItem e) {
for (InventoryItemAddedListener element : listeners) {
element.inventoryItemAdd(e);
}
}
#Override
public void add(int index, InventoryItem element) {
super.add(index, element);
fireInventoryItemAdded(element);
}
#Override
public boolean addAll(Collection c) {
boolean addAll = super.addAll(c);
fireInventoryItemAdded(c);
return addAll;
}
private void fireInventoryItemAdded(Collection c) {
for (InventoryItem inventoryItem : c) {
fireInventoryItemAdded(inventoryItem);
}
}
#Override
public boolean addAll(int index, Collection c) {
boolean addAll = super.addAll(index, c);
fireInventoryItemAdded(c);
return addAll;
}
}

Searching extracted data from a file, stored into an array for answers. IO

I have successfully extracted data from 2 files and stored them in array objects in their respective classes. This is some of my data that i have stored in array objects:
2005,Arsenal,ManU,Arsenal,WestHam,Y,2,3,40000
2006,ManU,Chelsea,ManU,WestHam,N
2007,ManU,Arsenal,ManU,WestHam,Y,1,0,260000
2008,Chelsea,ManU,Chelsea,Swansea,Y,4,0,285630
2009,Chelsea,ManCity,Chelsea,Swansea,N
Each comma represents a different column. This is is my code to store it:
try{
Scanner kd = new Scanner(file);
while(kd.hasNext()){
String data = kd.nextLine();
String [] values = data.split(",");
String year = values[0];
String wScore = "N/A" , lScore = "N/A", crowd = "N/A";
if(inputYears.equals(year))
{
g.setPremier(values[1]);
g.setLosing(values[2]);
I did as suggested by some of the users but the only problem now is im getting the winner as blank.For example:
Year: 2005
Premier:
It should be:
Premier: Arsenal
Anyway i can fix that?
Well, if the users are going to query only by the year, then you should have a map with the year as a key.
In the init phase, try doing something like this:
Map<String, ArrayList<String>> map= new HashMap<String, ArrayList<String>>();
while(kd.hasNext()){
String data = kd.nextLine();
String [] values = data.split(",");
String year = values[0];
String premiers = values[1];
//String otherStuff= values[2]; and so on
ArrayList<String> temp= new ArrayList<String>();
temp.add(premiers);
//temp.add(otherStuff);
map.put(year, temp);
}
Later on, you can query like this:
ArrayList<String> values= map.get(userInputYear);
String winner= values.get(0);
No collections? Tough teacher you got there....
In the absence of a Map you could try creating a separate getPremiershipChampion method.
Like this:
public PremiershipYear getPremiershipChampion (String userYear, String[] kd) {
while(kd.hasNext()){
String data = kd.nextLine();
String [] values = data.split(",");
String year = values[0];
if (userYear.equals(year)) {
PremiershipYear py = new PremiershipYear();
py.setWinner(values[1]);
py.setRunnerUp(values[2]);
// Set whatever you need to here...
return py;
}
}
return null;
}
...then call it like this:
PremiershipYear year = getPremiershipChampion (userYear, kd);
// Get the winner
if (year != null) {
System.out.println("Winner for "+userYear+"="+year.getWinner());
}
Here is the PremiershipYear class:
public class PremiershipYear {
private String winner;
private String runnerUp;
private String third;
private String fourth;
private String faCupWinner;
private int someScore;
public String getWinner() {
return winner;
}
public void setWinner(String winner) {
this.winner = winner;
}
public String getRunnerUp() {
return runnerUp;
}
public void setRunnerUp(String runnerUp) {
this.runnerUp = runnerUp;
}
public String getThird() {
return third;
}
public void setThird(String third) {
this.third = third;
}
public String getFourth() {
return fourth;
}
public void setFourth(String fourth) {
this.fourth = fourth;
}
public String getFaCupWinner() {
return faCupWinner;
}
public void setFaCupWinner(String faCupWinner) {
this.faCupWinner = faCupWinner;
}
public int getSomeScore() {
return someScore;
}
public void setSomeScore(int someScore) {
this.someScore = someScore;
}
}
You can muck about with this to make it more efficient e.g. make kd class level, but this should give you the general idea!
Use a Map.
If you only have one year per line, use a HashMap<String, String> with the year as key and the team as value.
If you have many lines with identical years, use a HashMap<String, ArrayList<String>> with the year as key and the team*s* as values.
In the latter case, you must ensure the value is initialized. If not, you initialize it and ad d the current team. If it was already initialized, you get the value by year and add the current team to it.
Once you have the user input, you can query your Map's key set...
to verify it contains the user input, and if so...
to display the team / enumerate every team listed for that year
you could make a class to represent a record of your data
class Data
{
private String year;
private String winner;
...
Data(String year, String winner) { ... }
}
then you can fill a Map which associates a year with some data which makes looking-up the year a bit easier.
Map<String, Data> m = new HashMap<String, Data>();
while(kd.hasNext())
{
String[] arr = kd.nextLine().split(",");
Data d = new Data(arr[0], arr[1])
m.put(arr[0], d);
}
but even if you just had a List<Data> or Data[] etc you could still do something like
for (Data d : listOfData)
{
if (d.getYear().equals(yearToFind)) return d;
}
to find the year

Categories