How to join multiple single arrays into one large single array - java

So I gathered tokens from multiple lines of a text file and put those tokens into an array called tokens. With this code.
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
if ((line = scanner.nextLine()).charAt(0) != '#') {
tokens = line.split(",");
}
}
(Its all in a try catch block)
I need to put all of those String tokens into a single array, how would I do this.
My new array is stringTokens [] = new String [countLines *4].
The while loop redefines the elements in tokens with each iteration, how do I save those old elements in stringTokens and add the new elements tokens will get into stringTokens as well.

You can use an ArrayList<String> for that, and when you need it as array, you can convert it to one:
ArrayList<String> list = new ArrayList<>();
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
if ((line = scanner.nextLine()).charAt(0) != '#') {
for(String s : line.split(",")) {
list.add(s);
}
}
}
stringTokens = list.toArray(new String[0]);

You should look into using ArrayLists. They are essentially mutable arrays, with no specified size (the array "grows"* as you add elements.) and adding each token to your list of strings.
ArrayList<String> stringTokens = new ArrayList<String>();
...
for(String s : line.split(",")) {
stringTokens.add(s);
}
*Capacity doubles when needed.

Related

Java: Removing item from array because of character

Lets say you have an array like this: String[] theWords = {"hello", "good bye", "tomorrow"}. I want to remove/ignore all the strings in the array that have the letter 'e'. How would I go about doing that? My thinking is to go:
for (int arrPos = 0; arrPos < theWords.length; arrPos++) { //Go through the array
for (int charPos = 0; charPos < theWords[arrPos].length(); charPos++) { //Go through the strings in the array
if (!((theWords[arrPos].charAt(charPos) == 'e')) { //Finds 'e' in the strings
//Put the words that don't have any 'e' into a new array;
//This is where I'm stuck
}
}
}
I'm not sure if my logic works and if I'm even on the right track. Any responses would be helpful. Many thanks.
One easy way to filter an array is to populate an ArrayList with if in a for-each loop:
List<String> noEs = new ArrayList<>();
for (String word : theWords) {
if (!word.contains("e")) {
noEs.add(word);
}
}
Another way in Java 8 is to use Collection#removeIf:
List<String> noEs = new ArrayList<>(Arrays.asList(theWords));
noEs.removeIf(word -> word.contains("e"));
Or use Stream#filter:
String[] noEs = Arrays.stream(theWords)
.filter(word -> !word.contains("e"))
.toArray(String[]::new);
You can directly use contains() method of String class to check if "e" is present in your string. That will save your extra for loop.
It would be simple if you use ArrayList.
importing import java.util.ArrayList;
ArrayList<String> theWords = new ArrayList<String>();
ArrayList<String> yourNewArray = new ArrayList<String>;//Initializing you new array
theWords.add("hello");
theWords.add("good bye");
theWords.add("tommorow");
for (int arrPos = 0; arrPos < theWords.size(); arrPos++) { //Go through the array
if(!theWords.get(arrPos).contains("e")){
yourNewArray.add(theWords.get(arrPos));// Adding non-e containing string into your new array
}
}
The problem you have is that you need to declare and instantiate the String array before you even know how many elements are going to be in it (since you wouldn't know how many strings would not contain 'e' before going through the loop).
Instead, if you use an ArrayList you do not need to know the required size beforehand. Here is my code from start to end.
String[] theWords = { "hello", "good bye", "tomorrow" };
//creating a new ArrayList object
ArrayList<String> myList = new ArrayList<String>();
//adding the corresponding array contents to the list.
//myList and theWords point to different locations in the memory.
for(String str : theWords) {
myList.add(str);
}
//create a new list containing the items you want to remove
ArrayList<String> removeFromList = new ArrayList<>();
for(String str : myList) {
if(str.contains("e")) {
removeFromList.add(str);
}
}
//now remove those items from the list
myList.removeAll(removeFromList);
//create a new Array based on the size of the list when the strings containing e is removed
//theWords now refers to this new Array.
theWords = new String[myList.size()];
//convert the list to the array
myList.toArray(theWords);
//now theWords array contains only the string(s) not containing 'e'
System.out.println(Arrays.toString(theWords));

Grouping of words from a text file to Arraylist on the basis of length

public class JavaApplication13 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
BufferedReader br;
String strLine;
ArrayList<String> arr =new ArrayList<>();
HashMap<Integer,ArrayList<String>> hm = new HashMap<>();
try {
br = new BufferedReader( new FileReader("words.txt"));
while( (strLine = br.readLine()) != null){
arr.add(strLine);
}
} catch (FileNotFoundException e) {
System.err.println("Unable to find the file: fileName");
} catch (IOException e) {
System.err.println("Unable to read the file: fileName");
}
ArrayList<Integer> lengths = new ArrayList<>(); //List to keep lengths information
System.out.println("Total Words: "+arr.size()); //Total waords read from file
int i=0;
while(i<arr.size()) //this loop will itrate our all the words of text file that are now stored in words.txt
{
boolean already=false;
String s = arr.get(i);
//following for loop will check if that length is already in lengths list.
for(int x=0;x<lengths.size();x++)
{
if(s.length()==lengths.get(x))
already=true;
}
//already = true means file is that we have an arrayist of the current string length in our map
if(already==true)
{
hm.get(s.length()).add(s); //adding that string according to its length in hm(hashmap)
}
else
{
hm.put(s.length(),new ArrayList<>()); //create a new element in hm and the adding the new length string
hm.get(s.length()).add(s);
lengths.add(s.length());
}
i++;
}
//Now Print the whole map
for(int q=0;q<hm.size();q++)
{
System.out.println(hm.get(q));
}
}
}
is this approach is right?
Explanation:
load all the words to an ArrayList.
then iterate through each index and check the length of word add it to an ArrayList of strings containing that length where these ArrayList are mapped in a hashmap with length of words it is containing.
Firstly, your code is working only for the files which contain one word by line as you're processing whole lines as words. To make your code more universal you have to process each line by splitting it to words:
String[] words = strLine.split("\\s+")
Secondly, you don't need any temporary data structures. You can add your words to the map right after you read the line from file. arr and lengths lists are actually useless here as they do not contain any logic except temporary storing. You're using lengths list just to store the lengths which has already been added to the hm map. The same can be reached by invoking hm.containsKey(s.length()).
And an additional comment on your code:
for(int x=0;x<lengths.size();x++) {
if(s.length()==lengths.get(x))
already=true;
}
when you have a loop like this when you only need to find if some condition is true for any element you don't need to proceed looping when the condition is already found. You should use a break keyword inside your if statement to terminate the loop block, e.g.
for(int x=0;x<lengths.size();x++) {
if(s.length()==lengths.get(x))
already=true;
break; // this will terminate the loop after setting the flag to true
}
But as I already mentioned you don't need it at all. That is just for educational purposes.
Your approach is long, confusing, hard to debug and from what I see it's not good performance-wise (check out the contains method). Check this:
String[] words = {"a", "ab", "ad", "abc", "af", "b", "dsadsa", "c", "ghh", "po"};
Map<Integer, List<String>> groupByLength =
Arrays.stream(words).collect(Collectors.groupingBy(String::length));
System.out.println(groupByLength);
This is just an example, but you get the point. I have an array of words, and then I use streams and Java8 magic to group them in a map by length (exactly what you're trying to do). You get the stream, then collect it to a map, grouping by length of the words, so it's gonna put every 1 letter word in a list under key 1 etc.
You can use the same approach, but you have your words in a list so remember to not use Arrays.stream() but just .stream() on your list.

How to only get the lines you want from an arraylist depending on how they start, IN JAVA

I have a very long string containing GPS data but this is not important. What I need to do is separate the string which is in an arraylist (one big string) into multiple pieces.
The tricky part is that the string is made up of multiple 'gps sentances' and I only require two types of these sentences.
The types I need start with $GPSGSV and $GPSGGA. Basically I need to dump ONLY THESE sentences into another arraylist while leaving all the rest behind.
The new arraylist must be in line-by-line form so that each sentence is followed by a new line.
Each sentence also ends in one white space which could be helpful when splitting up. The arraylist data is shown below. - This is printed from the arraylist.
[$GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A,
$GPRMC,151018.000,A,5225.9627,N,00401.1624,W,0.11,104.71,210214,,*14,
$GPGGA,151019.000,5225.9627,N,00401.1624,W,1,09,1.0,38.9,M,51.1,M,,0000*72,
$GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A,
$GPGSV,3,1,12,26,80,302,44,09,55,063,40,05,53,191,39,08,51,059,37*79,
$GPGSV,3,2,12,28,43,112,34,15,40,284,42,21,18,305,33,07,18,057,27*7E,
$GPGSV,3,3,12,10,05,153,,24,05,234,38,18,05,318,22,19,05,035,*79,
$GPRMC,151019.000,A,5225.9627,N,00401.1624,W,0.10,105.97,210214,,*1D,
$GPGGA,151020.000,5225.9627,N,00401.1624,W,1,09,1.0,38.9,M,51.1,M,,0000*78,
$GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A,
$GPRMC,151020.000,A,5225.9627,N,00401.1624,W,0.12,105.18,210214,,*12,
$GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A,
$GPRMC,151021.000,A,5225.9626,N,00401.1624,W,0.11,99.26,210214,,*28,
$GPGGA,151022.000,5225.9626,N,00401.1623,W,1,09,1.0,38.9,M,51.1,M,,0000*7C,
$GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A,
$GPRMC,151022.000,A,5225.9626,N,00401.1623,W,0.11,109.69,210214,,*1F,
The data continues up to 2000 sentences.
Any help would be great. Thanks
EDITS ------
Looking back at what I have.. It may be best if I just read in the lines (as the file is formatted to be one sentence per line) which start with either the GSV or the GGA tag. In the buffered reader section of the method, how could I go about doing that? Here is some of my code ....
try {
File gpsioFile = new File(gpsFile);
FileReader file = new FileReader(gpsFile);
BufferedReader buffer = new BufferedReader(file);
StringBuffer stringbuff = new StringBuffer();
String ans;
while ((ans = buffer.readLine()) != null) {
gps.add(ans);
stringbuff.append(ans);
stringbuff.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
}
From this could I get an Arraylist with just the GGA and GSV sentences/lines but in the same order that they were from the file?
Thanks
OK, I'd first start by splitting your string into individual lines with spilt():
String[] split = "$GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A,".split(",");
you can also use "\n" as a split delimiter instead of ",". This will give you an array over which you can iterate.
List<String> filtered = new ArrayList<String>()
for (String item, split) {
if (item.startsWith("$GPGSA")) {
filtered.add(item);
}
}
filtered would be a new Array with the items you want to keep.
This approach works with JDK 6+. In JDK 8, this kind of problem can be solved more elegantly with the stream API.
My understanding is that you've got an ArrayList with a single String element. That String is a comma separated list of values. So step one is to extract the string and split it into it's constituent parts. Once you've done that you can process the each item in turn.
private static List<List<String>> splitData(final ArrayList<String> data) {
final List<List<String>> filteredData = new ArrayList<List<String>>();
String fullText = data.get(0);
String[] splitData = fullText.split(",");
List<String> currentList = null;
for (int i = 0;i < splitData.length; i++) {
final String next = splitData[i];
if (startTags.contains(next)) {
if (interestingStartTags.contains(next)) {
currentList = new ArrayList<String>();
filteredData.add(currentList);
} else {
currentList = null;
}
}
if (currentList != null) {
currentList.add(next);
}
}
return filteredData;
}
The two static Set<String> provide the set of all 'gps sentence' start tags and also the set of ones you're interested in. The split data method uses startTags to determine if it has reached the start of a new sentence. If the new tag is also interesting, then a new list is created and added to the List<List<String>>. It is this list of lists that is returned.
If you don't know all of the strings you want to use as 'startTag' then you could next.startsWith("$GP") or similar.
Reading the file
Looking at the updated question of how to read the file you could remove the StringBuffer and instead simply add each line you read to an ArrayList. The code below will step over any lines that do not start with the two tags you are interested in. The order of the lines within lineList will match the order they are found in the file.
FileReader file = new FileReader(gpsFile);
BufferedReader buffer = new BufferedReader(file);
String ans;
ArrayList<String> lineList = new ArrayList<String>();
while ((ans = buffer.readLine()) != null) {
if (ans.startsWith("$GPSGSV")||ans.startsWith("$GPSGGA")) {
lineList.add(ans);
}
}

how to work with Multidimensional arraylist?

Hey guys sorry i'm a noob at java but im trying to make something and i need a multidimensional array list. It must be implemented into the following code:
public static void OpenFile() {
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
int retrival = chooser.showOpenDialog(null);
if (retrival == JFileChooser.APPROVE_OPTION) {
try (BufferedReader br = new BufferedReader(new FileReader(
chooser.getSelectedFile()))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
if (sCurrentLine.equals("")) {
continue;
} else if (sCurrentLine.startsWith("Question")) {
System.out.println(sCurrentLine.split(":")[1]);
//add to [0] in array ArrayList
} else if (sCurrentLine.startsWith("Answer")) {
System.out.println(sCurrentLine.split(":")[1]);
//add to [1] in array ArrayList
} else if (sCurrentLine.startsWith("Category")) {
System.out.println(sCurrentLine.split(":")[1]);
//add to [2] in array ArrayList
} else if (sCurrentLine.startsWith("Essay")) {
System.out.println(sCurrentLine.split(":")[1]);
//add to [3] in array ArrayList
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
All the [1] index's of the strings i split need to go into a multidimesional array in this order: question, answer, category, essay.
So i am currently using a normal multidimensional array but you cant change the values of it easily. What i want my multidimensional arraylist to look like is this:
MultiDimensional ArrayList
[0]: questions(it may be over 100 of them.)
[1] answers(it may be over 100 of them.)
[2] category(it may be over 100 of them.)
[3] essay(it may be over 100 of them.)
Seems like an assignment with List of List.
Here is the psuedo code. Try to implement rest.
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
First thing you have to do is take 4 fresh ArrayLists
ArrayList<String> qtns= new ArrayList<String>>();
ArrayList<String> answrs= new ArrayList<String>>();
--
--
Add all of them to main list
array.add(qtns);
--
--
Then now filling them like
else if (sCurrentLine.startsWith("Question")) {
System.out.println(sCurrentLine.split(":")[1]);
//add to [0] in array ArrayList
array.get(0).add(sCurrentLine.split(":")[1]);//get first list(which is qtns list) and add to it.
} else if (sCurrentLine.startsWith("Answer")) {
System.out.println(sCurrentLine.split(":")[1]);
//add to [1] in array ArrayList
array.get(1).add(sCurrentLine.split(":")[1]);//get second list(which is answers list) and add to it.
}
-- -
---
So that in the end you'll have a list of list which contains the data.
array is an array of four elements (or will be, after you set it up--see below). Each of the elements is a reference to another ArrayList, i.e. an ArrayList<String>. To modify the inner ArrayList, first you need to get the reference to it, which you do with the get method:
array.get(0)
for the [0] list, or array.get(1) for the [1] list, and so on. The result will be an ArrayList<String>. Now you can perform methods on that; to add a String to the end of the ArrayList<String>:
array.get(0).add("String to add");
etc.
Actually, now that I look at it, you'll need to set up the four elements of array first. Each element will be set to a new ArrayList<String>:
for (int i = 0; i < 4; i++)
array.add(new ArrayList<String>());
Do this at the top of the method.
This is a really bad design. You should create a custom class, with the separate types of rows as fields (maybe call it Question), and then use a List<Question> to store the individual question objects. This will make it clearer, and safer, to work with in the future.
You can have a HashMap with key as (Questions,Answers..) and ArrayList as value
HashMap <String,ArrayList<String>> array = new HashMap<String,ArrayList<String>>();
if(array.containsKey("Question")){
array.get("Question").add(sCurrentLine.split(":")[1]);
}else{
ArrayList<String> questions = new ArrayList<String>();
questions.add(sCurrentLine.split(":")[1]);
array.put("Question",questions );
}
Modification In your Code
public static void OpenFile() {
HashMap <String,ArrayList<String>> array = new HashMap<String,ArrayList<String>>();
int retrival = chooser.showOpenDialog(null);
if (retrival == JFileChooser.APPROVE_OPTION) {
try (BufferedReader br = new BufferedReader(new FileReader(
chooser.getSelectedFile()))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
if (sCurrentLine.equals("")) {
continue;
} else if (sCurrentLine.startsWith("Question")) {
System.out.println(sCurrentLine.split(":")[1]);
if(array.containsKey("Question")){
array.get("Question").add(sCurrentLine.split(":")[1]);
}else{
ArrayList<String> questions = new ArrayList<String>();
questions.add(sCurrentLine.split(":")[1]);
array.put("Question",questions );
}
//add to [0] in array ArrayList
} else if (sCurrentLine.startsWith("Answer")) {
System.out.println(sCurrentLine.split(":")[1]);
//add to [1] in array ArrayList
//Do the same as above if condition with Answer as Key
} else if (sCurrentLine.startsWith("Category")) {
System.out.println(sCurrentLine.split(":")[1]);
//add to [2] in array ArrayList
} else if (sCurrentLine.startsWith("Essay")) {
System.out.println(sCurrentLine.split(":")[1]);
//add to [3] in array ArrayList
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Once you created a 2D array, you also need to create 4 1D arrays.
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
// 1D array for "Question"
array.add(new ArrayList<String>());
// 1D array for "Answer"
array.add(new ArrayList<String>());
// 1D array for "Category"
array.add(new ArrayList<String>());
// 1D array for "Essay"
array.add(new ArrayList<String>());
Let's say if you need to add one item to the question array, then you should do:
array.get(i).add(...);
where i = 0. The range of i is from 0 to 3, which corresponds to the 4 enumerations.
You should use another data structure to achieve that, Use a Map<String,List<String>> where the possible keys are Question,Answers,Category,Essay
Then in your code you can remove all unnecessary if-else
Example with your code:
public static void openFile() {
Map<String,List<String>> map = new HashMap<>();
// here you put the keys, you can do it when you read the file based in your input too dynamically
map.put("Question",new ArrayList<>());
map.put("Answers",new ArrayList<>());
map.put("Category",new ArrayList<>());
map.put("Essay",new ArrayList<>());
int retrival = chooser.showOpenDialog(null);
String[]array = null;
if (retrival == JFileChooser.APPROVE_OPTION) {
try (BufferedReader br = new BufferedReader(new FileReader(
chooser.getSelectedFile()))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
if (sCurrentLine.equals("")) {
continue;
}
array = sCurrentLine.split(":");
if(map.containsKey(array[0])){
map.get(array[0]).add(array[1]);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
You can see this way is much more cleaner and readable.

How to make a method for searching from array and print entire arraybox?

I could use some help with a part of a code I am working on.
I made a method which I think transformed every line of my .txt file into separate elements in an Array. However, I now want to be able to search in them and make the program print the entire element. ie: one of the lines reads: Crow, M, Kansas, june2012
I think I was able to make it into an array. Now I want to be able to search for "crow" and be able to get all the elements with that word in them printed alongside the rest of the String in the element.
The code I have so far:
System.out.println("Her kan du soke etter registrerigner etter fugletype");
try {
Scanner sc = new Scanner(new File("fugler.txt"));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
String[] arr = lines.toArray(new String[lines.size]);
}catch (Exception e) {
}
As others have already pointed out, you don't need to put your lines into an array since you already have them in an ArrayList.
If you want to "search" lines and only print certain ones you could use contains:
try {
Scanner sc = new Scanner(new File("fugler.txt"));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
for (String line : lines) {
if(line.contains("yourSearchString")) {
System.out.println(line);
}
}
} catch (Exception e) {
}
First of all, you don't need to put the lines in an array. You already have them in a list.
You could print them as they come in:
while (sc.hasNextLine() {
String currentLine = sc.nextLine();
System.out.println(currentLine);
lines.add(currentLine);
}
Or, you could just print all the lines in your list:
for (String line : lines) {
System.out.println(line);
}
In addition to the other problems, if you want to have an array, you should replace this:
String[] arr = lines.toArray(new String[0]);
with this:
String[] arr = lines.toArray(new String[lines.size()]);
Your array that gets passed in is the array that will be populated by toArray, so it needs to be big enough to hold all the elements.
If you want to search for some value line, you can use the original ArrayList<String>:
// returns the index of the element, ie. its zero-based line number
int index = lines.indexOf(line);
To print them all, just loop through them all:
for(String l : lines) {
System.out.println(l);
}

Categories