I have 2 java lists
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
I load some data from the database to the first one and from diffrent database to the second one.
The strings in the lists look exactly the same:
3441134 China Ap F
3441134 China Ap F
But when I check:
if(list1.get(1).equals(list2.get(1))){
logger.info("true");
}
else{
logger.info("false")
}
I always get
false
Can somebody say why? I checked white spaces and it's the same too.
I think is something related with character encoding, you may be seeing the same string in console and debug but internally they have a extra invisible byte because of the encoding.
Try to look at: Invisible characters in Java Strings you will understand what i am saying.
Related
I am new to Java 8 and when I am trying to put a filter for all those cities which contains one letter. It doesn't work for me. However, when I run it with old approach it works.
List<String> cityList = new ArrayList<>();
cityList.add("Noida");
cityList.add("Gurgaon");
cityList.add("Denver");
cityList.add("London");
cityList.add("Utah");
cityList.add("New Delhi");
System.out.println(cityList);
/* Prior to Java 8 Approach */
for (String city : cityList) {
if(city.contains("a")){
System.out.println(city + " contains letter a");
}
}
/* Java 8 Approach */
System.out.println(Stream.of(cityList).filter(str -> str.contains("a")).collect(Collectors.toList()));
Here is the output
Noida contains letter a
Gurgaon contains letter a
Utah contains letter a
[]
Can you please explain me where am I am making mistakes.
Thanks in advance !
You'll need to use cityList.stream() rather than Stream.of(cityList). Reason being that currently, Stream.of(cityList) returns a Stream<List<String>> whereas you want Stream<String>. You can still accomplish your task by using your current approach but you'll need to flatten the Stream<List<String>> into Stream<String> (I do not recommend as it causes un-necessary overhead hence it's better to use cityList.stream()).
That said, here is how you should go about accomplishing your task:
System.out.println(cityList.stream().filter(str -> str.contains("a")).collect(Collectors.toList()));
Stream.of(cityList) creates a Stream<List<String>> having a single element - your input List.
You need to use cityList.stream() in order to get a Stream<String> contaning the elements of your input List.
System.out.println(cityList.stream().filter(str -> str.contains("a")).collect(Collectors.toList()));
outputs
[Noida, Gurgaon, Utah]
The only reason you code passed compilation is that both List and String have a contains method that returns a boolean.
Relatively new to programming here so I apologize if this is rather basic.
I am trying to convert string lines into actual variables of different types.
My input is a file in the following format:
double d1, d2 = 3.14, d3;
int a, b = 17, c, g;
global int gInt = 1;
final int fInt = 2;
String s1, s2 = "Still with me?", s3;
These lines are all strings at this point. I wish to extract the variables from the strings and receive the actual variables so I can use and manipulate them.
So far I've tried using regex but I'm stumbling here. Would love some direction as to how this is possible.
I thought of making a general type format for example:
public class IntType{
boolean finalFlag;
boolean globalFlag;
String variableName;
IntType(String variableName, boolean finalFlag, boolean globalFlag){
this.finalflag = finalFlag;
this.globalFlag = globalFlag;
this.variableName = variableName;
}
}
Creating a new wrapper for each of the variable types.
By using and manipulating I would like to then compare between the wrappers I've created and check for duplicate declarations etc'.
But I don't know if I'm on the right path.
Note: Disregard bad format (i.e. no ";" at the end and so on)
While others said that this is not possible, it actually is. However it goes somewhat deep into Java. Just search for java dynamic classloading. For example here:
Method to dynamically load java class files
It allows you do dynamically load a java file at runtime. However your current input does not look like a java file but it can easily be converted to one by wrapping it with a small wrapper class like:
public class CodeWrapper() {
// Insert code from file here
}
You can do this with easy file or text manipulations before loading the ressource as class.
After you have loaded the class you can access its variables via reflection, for example by
Field[] fields = myClassObject.getClass().getFields();
This allows you to access the visibility modifier, the type of the variable, the name, the content and more.
Of course this approach presumes that your code actually is valid java code.
If it is not and you are trying to confirm if it is, you can try to load it. If it fails, it was non-valid.
I have no experience with Java, but as far as my knowledge serves me, it is not possible to actually create variables using a file in any language. You'll want to create some sort of list object which can hold a variable amount of items of a certain type. Then you can read the values from a file, parse them to the type you want it to be, and then save it to the list of the corresponding type.
EDIT:
If I were you, I would change my file layout if possible. It would then look something like this:
1 2 3 4 //1 int, 2 floats, 3 booleans and 4 strings
53
3.14
2.8272
true
false
false
#etc.
In pseudo code, you would then read it as follows:
string[] input = file.Readline().split(' '); // Read the first line and split on the space character
int[] integers = new int[int.Parse(input[0])] // initialise an array with specefied elements
// Make an array for floats and booleans and strings the same way
while(not file.eof) // While you have not reached the end of the file
{
integers.insert(int.Parse(file.ReadLine())) // parse your values according to the size which was given on the first line of the file
}
If you can not change the file layout, then you'll have to do some smart string splitting to extract the values from the file and then create some sort of dynamic array which resizes as you add more values to it.
MORE EDITS:
Based on your comment:
You'll want to split on the '=' character first. From the first half of the split, you'll want to search for a type and from the second half, you can split again on the ',' to find all the values.
I am making a program to help students learning a second language for my school. The main function of this program will be flash cards. What I am having trouble with is figuring out how to store said words and their respective translations. Would an array be the best way to do this? My teacher has talked for a whole two seconds on arrays so I only know the general purpose of them.
Also how would I call those stored, corresponding strings so the user can see them? If there is some better and more efficient way to store them, I would love to find out.
Edit: I also plan to allow the user to input the words through a text field or something of the sort, if that changes the answer.
I think that you should store the said words and their respective translations into a HashMap with said word is key, and value is the translation. And to get the stored, just find by key.
A Map<String, String> would be the perfect data type for mapping one String to another. I would definitely read up on the documentation here if I were you.
For example:
Map<String, String> translatedWords = new HashMap<>();
translatedWords.put("Hello", "Hola");
System.out.println(translatedWords.get("Hello"));
>> "Hola"
It can be taken as a simple one and challenging one also. If you expecting a simple idea then you can use a Map. then store the key as first language word and value as second language word,These are the map implementations
HashMap (if you need more speed then use this implementation)
Map<String,String> translatedValues = new HashMap();
LinkedHahMap (If you need the data as the same oreder of insertion)
TreeMap (Less speed but sorted one)
You could use a 2D array, because it uses rows and columns. Consider the following example, it is Spanish:
String[][] array = new String[][]{
{"You","Tu"},
{"Sandwich","Bocadillo"},
{"You eat a sandwich","Tu comes un bocadillo"}
};
Look at this Javadoc for more info: https://docs.oracle.com/cd/E58500_01/pt854pbh1/eng/pt/tpcr/task_CreatingandPopulatingMulti-DimensionalArrays-071663.html#topofpage
EDIT:
It looks like you are trying to have the user input their own words and translations... Unless you use file reading and writing, this is going to be a really difficult process. This is an example of a way to store translations via file writing, if I learn more about 2D ArrayLists, I'll get back to you.
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a word:");
String word = sc.nextLine();
//You can also use textfields: word = textfield.getText();
System.out.println("Please enter the translation:");
String trans = sc.nextLine();
//Always use UTF-8 if you are using any European or American alphabets
PrintWriter pw = new PrintWriter("lang.txt", "UTF-8");
/*
* You can name the file anyting you want, with any extension:
*"Cake.weirdFile, Juice.lump, Ilike.Chicken"
*it should be readable by Java as long as you use UTF-8
*/
pw.print(word);
pw.println(trans);
pw.close();
//Make sure to catch/throw FileNotFoundException & UnsupportedEncodingException
And you can read the file for flash card quizzes/reviews:
Scanner sc2 = new Scanner(new File("lang.txt"));
//Make sure to catch/throw FileNotFoundException
String[] wordAndTrans = sc2.nextLine().split(" ");
sc2.close();
System.out.println("The translation of '"
+ wordAndTrans[0] + "' is: '" + wordAndTrans[1] + "'");
Although this code works, I wouldn't suggest copy/pasting this because the way it is laid out might not be compatible with your code. This is merely an example usage of Scanners, PrintWriters, and String splitting so you can save your translations each to their own line in a file.
ResourceBundle
Also known as properties files
Don't clutter your code with Hashmaps and arrays. You also can have additional translations without editing any Java code
A properties file is a simple text file. You can create and maintain a properties file with just about any text editor
# This is the default LabelsBundle.properties file
s1 = computer
s2 = disk
s3 = monitor
s4 = keyboard
To support an additional Locale, your localizers will create a new properties file that contains the translated values. No changes to your source code are required, because your program references the keys, not the values.
# This is the LabelsBundle_de.properties file
s1 = Computer
s2 = Platte
s3 = Monitor
s4 = Tastatur
Use
Locale currentLocale;
ResourceBundle labels = ResourceBundle.getBundle("LabelsBundle", currentLocale);
String computer = labels.getString("s1");
My classes are the following: Room, Drawers, Shorts, Tops, and Socks. I have arrayLists roomList, drawerList, shortList, topList, and sockList in their designated classes. I also have a text file(room.txt) in which I need to read in the contents and store them in the appropriate arrayList.
The text file looks something like this:
Room 1, White,BlackStripes,3
Drawer 1,Black,Large,3,2,4
Drawer 2,White, Small,4,1,2
Short 1,Blue, M, 32
Short 2,Yellow, L, 34
Short 3, Orange, S, 28
Top 1,Green,L, 10
Sock 1, White, L, 20
Sock 2, Red, L, 18
Basically I'm having trouble putting the content in the right place. This is what my code looks like:
try{
Scanner read = new Scanner(new File("room.txt"));
while(read.hasNextLine())
{
Room myRoom = new Room();
Drawers myDrawers = new Drawer();
Shorts myShorts = new Short();
Tops myTops = new Tops();
Socks mySock = new Socks();
// What goes here, including comma delimeters, and counters etc
myRoom.setName(//What goes here);
myRoom.setColor();
myRoom.setStripes();
myRoom.SetDrawerAmount();
Room.roomList.add(myRoom);
myDrawers.setName();
myDrawers.setColor();
myDrawers.setSize();
myDrawers.setContainers();
myDrawers.setKnobs();
myDrawers.setItem();
Drawers.drawerList.add(myDrawers);
myShorts.setname();
myShorts.setColor();
myShorts.setSize();
myShorts.setNumSize();
Shorts.shortList.add(myShorts);
myTops.setName();
myTops.setColor();
myTops.setSize();
myTops.setNumSize();
Tops.topList.add(myTops);
mySocks.setName();
mySocks.setColor();
mySocks.setSize();
mySocks.setPairs();
Socks.sockList.add(mySocks);
}
}
catch (Exception e)
{
System.out.println("Error File Not Found");
}
Basically, I'm not sure how to format at it to know when I should add to roomList, or drawerList, or shortsList, or topsList, or socksList, since there are different numbers of lines and different numbers of content per line.
You must write a custom parser for that kind of files.
Your parser must read each line, then split the line by commas "," (see String.split() method). That gives you an String[] for each line.
Once you have the String[], compare the first element with "Rooms", "Drawers", etc... in a switch statement or if/else.
You must process each element of the String[] in order to classify your objects. Do this in a separate method. Your method should returns a Room, Drawer, Shorts, etc. to the caller, and so on...
You don't tell us what the classes Room, Drawer... look like so there is your problem :)
Why don't you use plain old lists?
List<Room> rlist= new ArrayList<Room>();
List<Drawer> dlist= new ArrayList<Drawer>();
so on and so forth, then it is this easy:
rlist.add(myRoom);
then on and on again
#eyp has good advice. In addition,
Scanner can be frustrating at times. If it works for you, go with it. Otherwise, read up on other java I/O classes like FileReader and BufferedReader. You can compose a BufferedReader and a FileReader (See the example in the BufferedReader documentation: Java Standard Edition Documentation.) It's almost as easy as using Scanner, it gives you the readLine() method you need, and it allows you to do more advanced I/O in the future.
If the different classes were subclasses of a common superclass, you could put a lot of the parsing into the superclass constructor to avoid repeating it for each subclass. Look at what each line in your text file is made up of, and I think you'll be able to recognize a common superclass. Then each subclass could handle the part that is specific to it.
I'm writing a personal program that will help my Dnd group and at the same time expand my java knowledge a little :) now part of that involves some arrays, and loading text into them from a text file. Now I have succeeded in that and with them all set statically it's all fine, since the end result will have lots of arrays I thought rather than making each array do all the leg work itself I would create an array handler method.
So I would do filetest(filename,arrayName) (ie filetest(table1,table1Array)
and it would make the array, but I'm stuck on one thing: How do I make the array using the name from arrayName?
It's pretty much got me stumped my so far failed code is:
public class arrayFileHandler {
public static void fileTest(String fileName,String arrayName) throws FileNotFoundException{
int a = 0;
System.out.println("test");
System.out.println(System.getProperty("user.dir")); //this is the folder where the file SHOULD be
Scanner testTable1 = new Scanner(new File("data/"+fileName+".txt")); //with luck this will load the file ! if i understand + correct!
//Scanner testTable1 = new Scanner(new File("C:/Dev/newjava/dnd/src/dnd/test.txt")); //this works but is no good for our needs
ArrayList<String> testTable = new ArrayList<String>(); //create the array list since at this stage we dont know how long the array will be
while(testTable1.hasNextLine()){ //see if the file we are using has a next line (could cause me issues if the txt has blank lines...hmmm)
String line = testTable1.nextLine(); //put that line into the string "line"
testTable.add(line); //add that line to the array list
System.out.println(line); //lets see what that line says
a++; //to help count the lines(not needed now)
speechHandler.speechSynth(2, 1, 0, 60, line); //a debug line
}
System.out.println("there are "+ a +" lines"); //print how many lines there are
String arrayName[] = new String [testTable.size()]; //create an array with the number of "slots" equal to the number of slots in the arraylist and named with the String in arrayName
arrayName = testTable.toArray(arrayName);//copy the arraylist to the array
System.out.println(arrayName[0]);
//System.out.println(tableList[2]);
speechHandler.speechSynth(2, 1, 0, 60, arrayName[2]); //also a debug line
}
Now the important line is String arrayName[] = new String [testTable.size()]; it's trying to create an array called arrayName, but I need it to be created with whatever name is in the string called arrayName, so in my example in the second paragraph it would be called table1Array.
Googling hasn't helped me much and I'm wondering if what I want to do is actually possible.
It's not possible and it also doesn't make any sense in your case. What's your goal? You're just creating a local variable, it doesn't matter which name did you choose. It'd only get complicated, because you'd need to access it using another variable (containing the name). I really don't see any usage in this.
If you were using some dynamic interpreted language, it could be done by using something like "eval", which would create variable with defined name at runtime. But in the Java, all code (including all variables etc) is compiled into bytecode and then executed. Do you see the problem? At compile time, the variable might not be recognized (because of missing name), and therefore it's not possible. Truth is, that bytecode doesn't contain local variable's names, but why JVM would have to solve issues like "isn't there already a variable with such a name" and so on? Bytecode would only get bigger, without actually bringing some new functionality.
If you really need this for some reason (and I just can't imagine which is that), I'd suggest you to use some sort of associative array, e.g. java.lang.Hashtable<>. It allows you to change names runtime.
From you last comment, if I understand right, you want to create arrays of strings based on the contents of text files.
You started with reading the lines into an ArrayList of Strings. I suggest you stick with ArrayLists, and not bother with arrays.
If you are going to read lots of files, I suggest you put your code which creates the ArrayLists into a method so you can call it as many times as you want, once for each file.
Below is such a function, copied from your code and modified where necessary (I removed the comments):
Here goes:
public List<String> getLinesFromFile(String filename) {
Scanner testTable1 = new Scanner(new File(filename));
List<String> testTable = new ArrayList<String>();
while(testTable1.hasNextLine()){
String line = testTable1.nextLine();
testTable.add(line);
}
return testTable;
}
You can call that as many times as you like. If you have lots of files, you can 'name' them the same as your filename by storing them in a Map:
First, create a Map whose keys are Strings (so we can look up by filename) and whose values are List (lists of strings - the content of the files)
Map<String, List<String>> fileContentMap = new HashMap<String, List<String>>();
Next, every time we read a file, add it to the Map:
String filename = // ... whatever file to read next
fileContentMap.put(filename, getLinesFromFile(filename));
Finally, when you want to retrieve them:
//retrieve lines from a file I read earlier:
List<String> lines = fileContentMap.get(filename);