Accessing Elements in an ArrayList of ArrayLists - java

I have an ArrayList of ArrayLists, and I'm trying to access the elements inside, and generally add, remove, replace, and get the items.
My code is below.
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class MarvelNetworkRearrange {
public static void main(String[] args) {
BufferedReader csvReader = null;
try {
String newLine;
ArrayList B = new ArrayList<ArrayList>();
csvReader = new BufferedReader(new FileReader("MARVEL P2P.csv"));
Integer i = 0;
while ((newLine = csvReader.readLine()) != null)
{
B.add(A(newLine));
}
File f = new File("MarvelRearranged.csv");
PrintWriter printWriter = new PrintWriter(f);
ArrayList<String> x = new ArrayList<String>();
x = B.get(0);
x.remove(0);
System.out.println(x);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (csvReader != null) csvReader.close();
}
catch (IOException newException)
{
newException.printStackTrace();
}
}
}
public static ArrayList<String> A(String fromCSV) {
ArrayList<String> csvResult = new ArrayList<String>();
if (fromCSV != null)
{
String[] splitData = fromCSV.split("\\s*,\\s*");
for (int i = 0; i < splitData.length; i++)
{
if (!(splitData[i] == null) || !(splitData[i].length() == 0))
{
csvResult.add(splitData[i].trim());
}
}
}
return csvResult;
}
}
I'm reading in a .csv file, and I'm attempting to rearrange the items in the .csv file in order to create a .csv file that I can use more effectively for a project. However, when I run this code, I get "error: incompatible types: Object cannot be converted to ArrayList" at "x = B.get(0);". I have also tried x.get(0).remove(0).
I am trying to remove the first element of the first ArrayList in the ArrayList B, so what am I doing wrong? The reason I'm trying to remove it is that the specified element is a blank space in the .csv (done intentionally when creating the original, as it was the space between the headers in a matrix).
Please help!

You have defined your ArrayList B without type, but ArrayList x has String type. Either you need to cast the type, or you need to follow below approach which is better:
Specify type of ArrayList B:
ArrayList<ArrayList<String>> B = new ArrayList<>();
To delete any element from your ArrayList, skip creating another object and point to an element of B, directly delete from B:
B.get(0).remove(0);

Related

Read integers from file and save two integers per index in a ArrayList

I have research about what I am trying to accomplish. This is my code, and here the main function is to read a file.txt which has integers separated by white spaces and they will be read one by one. However, I want to know... How Can I stored the integers inside a ArrayList, But in each index of the ArrayList there will be two integers instead of one, as usual?
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
int[] arr = readFile("address.txt");
System.out.println("The memory block generated is:");
System.out.println(Arrays.toString(arr));
}
// access this method in FIFO
public static int[] readFile(String file) { // this main method
try { // try and catch
File f = new File(file);
#SuppressWarnings("resource")
Scanner r = new Scanner(f); // read the file with scanner
int count = 0; // count for the integers
while(r.hasNextInt()) { // while keep reading
count++;
r.nextInt();
}
int[] array = new int[count];
#SuppressWarnings("resource")
Scanner readAgain = new Scanner(f); // read again
ArrayList<ArrayObjects> blockMem = new ArrayList<>(); // array size * we can use dynamic array
for(int i = 0; i < count; i++) {
// i want to iterate and save them
}
return array;
} catch(Exception fnf) {
System.out.println(fnf.getMessage() + "The file could not be open, try again");
System.exit(0);
}
return null;
} // method closed
}`
Create a new class with two integers.
class TwoIntegers{
int one,two;
TwoIntegers(int data1,int data2){
one = data1;
two = data2;
}
}
Now create an Arraylist of objects of type TwoIntegers
ArrayList<TwoIntegers> blockMem = new ArrayList<TwoIntegers>();
//now you can iterate and insert integers you need
blockMem.add(new TwoIntegers(1,2));
blockMem.add(new TwoIntegers(3,4));

Adding a value to a sorted array in Java 8

You are provided the following list that contains (semi-random) years from modern history. Save the list to a text file named “events.txt” Write a program that:
Reads in the file “events.txt”
Sorts it with the latest events first
Determines whether the founding of CMU in 1892 was considered a world historic event
If not so yet, adds the event to the list of events
Writes the new list of events to a file named “sorted_events.txt
import java.io.*;
import java.util.*;
public class EventSorter {
public static void main(String[] args) throws FileNotFoundException{
File file =new File("events.txt");
FileReader read = new FileReader(file);
LineNumberReader lines = new LineNumberReader(read);
Scanner readIn = new Scanner(file);
PrintWriter output = new PrintWriter("sorted_events.txt");
try{
//call for the file
//make sure it exists
if(file.exists()){
{
//first write this to determine the number of lines
int lineNumber = 0;
//gets the number of lines
while (lines.readLine() != null){
lineNumber++;
}
int[] event = new int[lineNumber];
int j = 0;
while(readIn.hasNext()){
event[j]=readIn.nextInt();
j++;
}
//sort the array
Arrays.sort(event);
boolean found;
for(int i = 0; i < event.length; i++){
if (event[i] == 1892){
//see if 1892 is on the list
System.out.println("CMU is a historic event");
found = true;
}
else{
addElement(event, 1892);
}
}
int[] sortedEvent = new int[lineNumber];
for(int k = 0; k < event.length; k++){
sortedEvent[k] = event[(event.length-1) - k];
System.out.println(sortedEvent[k]);
}
for(int print = 0 ; print < event.length; print++){
output.println(sortedEvent[print]);
}
}
readIn.close();
output.close();
lines.close();
}else{
System.out.println("File does not exist!");
}
}
catch(IOException e){
e.printStackTrace();
}
}
static int[] addElement(int[] a, int e) {
a = Arrays.copyOf(a, a.length + 1);
a[a.length - 1] = e;
return a;
}
}
I'm going to answer strictly to the title "Adding a value to a sorted array in Java 8". Two options can be:
Create a TreeSet or any SortedSet (or a structure based on a Binary Search Tree) from your array. This collection is sorted by default and any new items you add to it will keep it sorted.
Use something similar to binary search to find where in the array the new element should be placed.
This program does exactly what you want and answers the question of the teacher perfectly.
However, it's using several advanced techniques of Java and I strongly doubt that your teacher will give you any credit for it. So use it at your own risk.
The best you can do with this code is to read it, understand its concept and apply them in conjunction to what you know.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class EventSorter {
public static void main(String[] args) {
try {
Path inPath = Paths.get("events.txt");
Path outPath = Paths.get("sorted_events.txt");
int event = 1892;
Comparator<Integer> lastFirst = Comparator.<Integer>naturalOrder().reversed();
List<Integer> events = Files.lines(inPath).map(Integer::valueOf).sorted(lastFirst).collect(Collectors.toCollection(ArrayList::new));
int pos = Collections.binarySearch(events, event, lastFirst);
if (pos < 0) {
events.add(~pos, event);
}
Files.write(outPath, events.stream().map(Object::toString).collect(Collectors.toList()));
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
events.txt (input)
1982
1821
1934
1809
sorted_events.txt (output)
1982
1934
1892
1821
1809

How to arrange items in list from highest to lowest (word occurence using I/O)?

I have a working word occurrence program that took me a while to code (still new at Java) and I was wondering if I could get a little assistance. Here is my code that I have so far:
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class TestWordOccurenceProgram {
public static void main(String[] args) {
String thisLine = null;
try {
FileReader fr = new FileReader("myTextDocument.txt");
BufferedReader br = new BufferedReader(fr);
//List<String> wordList = new ArrayList<>();
List<String> words = new ArrayList<>();
// make ArrayList of integers
List<Integer> counts = new ArrayList<>();
String word = "";
while ((thisLine = br.readLine()) != null ) {
word = word.concat(thisLine);
word = word.concat(" ");
}
String[] wordList = word.split("\\s");
for (int i = 0; i < wordList.length; i++) {
String temp = wordList[i];
if(words.contains(temp)) {
int x = words.indexOf(temp);
int value = counts.get(x);
value++;
counts.set(x, value);
}
else {
words.add(temp);
counts.add(1);
}
}
for (int i = 0; i < words.size(); i++) {
System.out.println(words.get(i) + ": " + counts.get(i));
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
}
Here is what "myTextDocument.txt" has:
i am a rabbit
a happy rabbit am
yay i am a rabbit
a rabbit i am yay
Here is my output:
i: 3
am: 4
a: 4
rabbit: 4
happy: 1
yay: 2
Does anyone know if I could arrange these items from the highest number of word occurrences to the lowest number of word occurrences? Any help would be great!
You can use Map instead of List. and use compare method to sort map via its value.
refer this code :
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class PQ {
public static void main(String[] args) {
String thisLine = null;
try {
FileReader fr = new FileReader("D:\\test.txt");
BufferedReader br = new BufferedReader(fr);
HashMap<String,Integer> map = new HashMap<String,Integer>();
ValueComparator comparator = new ValueComparator(map);
TreeMap<String, Integer> treemap = new TreeMap<String, Integer>(comparator);
while((thisLine = br.readLine()) != null){
String[] str = thisLine.split("\\s+");
for(String s:str){
if(map.containsKey(s)){
Integer i = map.get(s);
i++;
map.put(s,i);
}else{
map.put(s, 1);
}
}
}
treemap.putAll(map);
System.out.println(treemap);
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
}
class ValueComparator implements Comparator<String>{
Map<String, Integer> base;
public ValueComparator(Map<String, Integer> base) {
this.base = base;
}
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
}
}
}
Rather than using two separate lists (one with words, one with counts), why not create a WordAndCount object that has something like getWord and getCount methods? This WordAndCount class can implement Comparable, where you do comparisons based on count. Then, you can store a single List<WordAndCount>, and just sort the single list using Collections.sort.
Roughly, the outline could look like this:
public class WordAndCount implements Comparable<WordAndCount> {
private String word;
private int count;
public WordAndCount(String word) {...}
public void incrementCount() {...}
public int compareTo(WordAndCount other) {...}
}
Wrapping up the combination into a single class makes this much easier to solve, as it provides the easy link between word and its count.
I would recommend using Collections in Java for this, but instead you can use temp variables.
So the idea is to sort by counts. Pseudo-code before outputting:
int tempCount;
String tempWord;
for (int i = 1; i < counts.size(); i++) {
if (counts.get(i) < counts.get(i-1)) {
tempCount = counts.get(i-1);
tempWord = words.get(i-1);
counts.set(i-1, i);
counts.set(i, tempCount);
words.set(i-1, i);
words.set(i, tempWord);
}
You'd need an extra loop around that to correctly order them but hopefully gives you the right idea.

Bubble sorting arraylis is not working

I'm trying to bubble sort car make and year, where I would have the car year sorted and if two car makes are in the same year, then they are sorted alphabetically. My program works up to the point where I call BubbleSorted(). It's giving me an error java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 and I don't know why. My program seems to be correct. Below is my program. I have 3 classes(main, bubblesortCars, GetCarInfo).
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.FileReader;
public class TheMain {
public static void main(String[] args) {
Scanner keyboard=new Scanner(System.in);
int choice;
boolean done = false;
try{
String filename1 = "Demo.txt";
FileReader inputFile = new FileReader(filename1);
//Instantiate the BufferedReader Class
BufferedReader bufferReader = new BufferedReader(inputFile);
ArrayList<GetCarInfo> CarList = new ArrayList();
//Variable to hold the one line data
String line;
StringTokenizer st;
int i=0;
// Read file line by line and print on the console
while ((line = bufferReader.readLine()) != null) {
st = new StringTokenizer(line, "\t");
st.nextToken();
st.nextToken();
String getMake = st.nextToken();
st.nextToken();
int getYear = Integer.parseInt(st.nextToken());
GetCarInfo temp;
temp = new GetCarInfo(getMake, getYear);
CarList.add(temp);
}
bufferReader.close();
BubbleSortCars Sorted = new BubbleSortCars();
Sorted.bubblesorted(CarList, 0, CarList.size());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
import java.util.ArrayList;
public class BubbleSortCars {
ArrayList <GetCarInfo> temp= new ArrayList();
public void bubblesorted(ArrayList <GetCarInfo> grabber, int began, int end){
for(int i =0; i<end-began-1; i++){
for(int j=began; j<(end-i-1); j++){
if(grabber.get(j).year > grabber.get(j+1).year){
temp.set(j, grabber.get(j));
grabber.set(j,grabber.get(j+1));
grabber.set(j+1, temp.get(j));
System.out.println("Success");
}
else if(grabber.get(j).year==grabber.get(j+1).year){
if((grabber.get(j).make).compareTo(grabber.get(j+1).make)>0){
temp.set(j, grabber.get(j));
grabber.set(j, grabber.get(j+1));
grabber.set(j+1, temp.get(j));
System.out.println("Success");
}
}
}
}
}
}
public class GetCarInfo {
int year;
String make;
public GetCarInfo(String newmake, int newyear){
make = newmake;
year = newyear;
}
}
Reason you get IndeOutOfBoundException is due to this line:
temp.set(j, grabber.get(j));
and your definition of arrayList.
ArrayList<GetCarInfo> temp = new ArrayList();
Here you are defining temp as arrayList without any element and you are trying to set an element at 0th location which is not defined. See this for your reference http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#set%28int,%20E%29
When you define temp as above it created with size 0 and jdk does check internally if index that you are trying to access is less than size then only it will allow you to access/set content.
So one way to avoid this, you define your temp arrayList in your method like:
ArrayList<GetCarInfo> temp = new ArrayList(grabber);
Or you could use grabber arrayList to do the sorting without any other data structure.
The problem is with the ArrayList temp. Please refer the Oracle documentation for the set method.
Here you don't need an ArrayList. User a simple GetCarInfo object as temp variable.

How to compare two array of object to check one array element with all values of other array?

I need to compare two array of object to check one array element with all values of other array. If I perform this way it shows NULL point exception at if statement.
package unlcomp;
import java.util.HashMap;
import java.util.List;
public class relation {
int rcount=0;
int r1count=0;
public String[] rel=new String[100];
relation rm[]=new relation[100];
relation rm1[]=new relation[100];
public String[] UW1=new String[1000];
public relation[] hash(String[] s,String[] s1,int rcount) {
for(int i=1;i<=rcount;i++) {
rm[i]=new relation();
rm[i].rel[i]=s[i];
rm[i].UW1[i]=s1[i];
}
return rm;
// System.out.println(rcount);
}
public relation[] hash1(String[] s,String[] s1,int r1count) {
for(int i=1;i<=r1count;i++) {
rm1[i]=new relation();
rm1[i].rel[i]=s[i];
rm1[i].UW1[i]=s1[i];
}
return rm1;
}
public void compare() {
relation r[]= rm;
relation r1[]=rm1;
for(int i=1;i<r.length;i++) {
for(int j=1;j<r1.length;j++) {
if(r1[i].rel[i].equals(r[j].rel[j])) {
System.out.println("true");
} else {
System.out.println("false");
}
}
}
}
}
I need to call this compare method from another class name.
This is the class that call the above functions..
package unlcomp;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Unlcomp {
public String[]rel;
public String[] UW1;
public String[] UW2=new String[100];
public String[] att1=new String[100];
public String[] att2=new String[100];
int i=0;
public String[] store=new String[500];
String pattern2="[-a-z0-9R:._-`&=*'`~\"\\+[\\s]]+[\\(]";
//String pattern = "[(]+[-a-z0-9R:._-`&=*'`~\"\\+[\\s]]+[\\(.,]";
String pattern = "[(]+[-a-z0-9R:_]+[(]+[-a-z0-9R:_-`&=*'`~&+,:;=?##'<>.^*%!-\"\\+[\\s]]+[)]+[\\.\\,\\:]";
String patterna = "[(]+[-a-z0-9R:_]+[(]+[-a-z0-9R:_-`&=*'`~&+,:;=?##'<>.^*%!-\"\\+[\\s]]+[)]+[\\,]";
//String pattern1="[,]+[-a-z0-9R:._-`&=*'`~\"\\+[\\s]]+[\\(.]";
String pattern1="[,]+[-a-z0-9R:_]+[(]+[-a-z0-9R_,>-`&=*'`~&+,:;=?##'<>.^*%!-\"\\+[\\s]]+[)]+[\\)\\.]";
//String pattern1a="[,]+[-a-z0-9R:_]+[(]+[-a-z0-9R_,>-`&=*'`~&+,:;=?##'<>.^*%!-\"\\+[\\s]]+[)]+[\\.]";
String pattern3="[\\)]+[\\.#]+[-a-z0-9R:._-`&=*'`~&+,:;=?##'<>.^*%!-\"\\+[\\s]]+[\\ ,]";
String pattern4="[\\)]+[\\.#]+[-a-z0-9R:._-`&=*'`~&+,:;=?##'<>.^*%!-\"\\+[\\s]]+[\\ )]";
Pattern r = Pattern.compile(pattern);
//Pattern ra = Pattern.compile(patterna);
Pattern r1 = Pattern.compile(pattern1);
//Pattern r1a = Pattern.compile(pattern1a);
Pattern r2 = Pattern.compile(pattern2);
Pattern r3 = Pattern.compile(pattern3);
Pattern r4 = Pattern.compile(pattern4);
String line;
relation obj=new relation();
private int rcount=0;
public void preprocess(String pathf1,String pathf2) throws Exception {
try {
Scanner scanner = new Scanner(new File(pathf1));
scanner.useDelimiter("###");
Scanner scanner1 = new Scanner(new File(pathf2));
scanner1.useDelimiter("###");
//BufferedReader br1 = new BufferedReader(new FileReader(pathf2));
if( scanner.hasNext()) {
if(scanner1.hasNext())
extract(scanner.next());
obj.hash(rel,UW1,rcount);
extract(scanner1.next());
obj.hash1(rel,UW1,rcount);
obj.compare();
}
scanner.close();
scanner1.close();
} catch (IOException e) {}
}
public void extract(String line) {
String [] lines=line.split("\n");
System.out.println(line);
rel=new String[100];
UW1=new String[100];
for(String line1: lines ) {
// rel=null;
// UW1=null;
//UW2=null;
//att1=null;
//att2=null;
Matcher m2 = r2.matcher(line1);
Matcher m1 = r1.matcher(line1);
Matcher m3 = r3.matcher(line1);
Matcher m4 = r4.matcher(line1);
Matcher m = r.matcher(line1);
if( m2.find()) {
rel[i]=m2.group();
rel[i]=rel[i].substring(0, rel[i].length()-1).trim();
rcount++;
//System.out.println(rel[i]);
}
if(m.find()) {
UW1[i]=m.group();
UW1[i]=UW1[i].substring(1, UW1[i].length()-1).trim();
}
i++;
}
}
public static void main(String[] args) throws Exception {
Unlcomp u=new Unlcomp();
String pathsr="E:/M.E/project/test.txt";
String pathdes="E:/M.E/project/test1.txt";
relation r=new relation();
u.preprocess(pathsr,pathdes);
}
}
This takes the values in rm it takes values in the object in array. I checked it using system.out.println() statement. I don't no how to return it. This is full coding of this concept, it reads input from the file.
The problem is definitely with nulls.
Either r1 or r1[i] or r1[i].rel[i] or r[j] might be null.
Check for nulls before you compare.
The if statement can only cast a nullpointer if the place in the array is Null else the method looks fine except you are only looking at one place in the sub array r1[i].rel[i]
if(r1[i].rel[i].equals(r[j].rel[j]))
{
System.out.println("true");
}
else
{
System.out.println("false");
Also lose the initialization of non static or final variables
public class relation {
int rcount;
int r1count;
public String[] rel;
relation rm[];
relation rm1[];
public String[] UW1;
Try this
relation rm[];
relation rm1[];
public relation[] hash(String[] s,String[] s1,int rcount)
{
rm = new relation[rcount];
rm1 = new relation[rcount];
...
}
// Do the same for hash1
In your code, unless rcount is 100, there will be null indices if rcount is less than 100 and you would get an IndexOutOfBounds if rcount is greater than 100.
These two things will occur because you declare your arrays as having 100 indices.
Also, here FYI
(r1[i].rel[i].equals(r[j].rel[j]))
You are actually comparing whether or not the Objects refer to the same Object reference, not that that are actually ==. I don't know if this affects your desired output or not.
As you are not updated you calling method how you are populating your relation[] of rm and rm1 and in compare method, two loop condtion end point is length, as you have defined the length as 100 for
public String[] rel = new String[100];
relation rm[] = new relation[100];
so loop will be itrated for 100 times and in if (r1[i].rel[i].equals(r[j].rel[j])) {
r1[i].rel[i] , here r1[i]
is null for the index when you have not intilized with the object in that position of the array,
and any operation you are trying to do on null is null.rel[i] will turn into NPE,
You need to take care for the
public String[] rel = new String[100];
relation rm[] = new relation[100];
ensure you have element in all the poistion.
extract(scanner.next());
obj.hash(rel,UW1,rcount);
in your preprocess method, are you sure always you are passing rCount as 100, if not then in hash method you don't have all element in the array of relation object. one way to check null before making comparison like
if ( r1[i] != null && r[j] != null && r1[i].rel[i].equals(r[j].rel[j]))

Categories