I have two Strings
String first = "value=[ABC,PQR,XYZ]"
String second="value=[ABC]"
I am trying to check the contains of string second into a string first.
I am using the below code
List<String> list = new Arraylist<>();
list.add(first);
if(list.contains(second)){
// do something
}
How to check contains in the list which has string with multiple ","?
Which data structure should I use for above problem?
Probably, you don't know how to work with lists in java...
In your case, you are adding a string "value=[ABC,PQR,XYZ]" to the list. Hence, you have a list with only one item.
If you want to create such a list ["ABC","PQR","XYZ"], you have to add these three elements one by one.
P.S. If you studied java basic, you wouldn't have such problems...
String first = "value=[ABC,PQR,XYZ]";
String second ="value=[ABC]";
String secondVal = second.substring(second.indexOf("[") + 1, second.indexOf("]"));
String[] firstArry = first.substring(first.indexOf("[") + 1, first.indexOf("]")).split(",");
boolean secondInFirst = false;
for (int i = 0; i < firstArry.length; i++) {
if (firstArry[i].equals(secondVal)) {
secondInFirst = true;
break;
}
}
I'm not sure why the first and second are formatted in such a way, however, assuming they are always formatted the same way ("value=[X,Y,Z]"),
We must break first up into a fixed list ("value=[ABC,PQR,XYZ]" -> {"ABC","PQR","XYZ"})
Format second to be readable ("value=[ABC]" -> "ABC")
Loop through firstArry and find matches
Store the result in secondInFirst
Related
I got 2 ArrayList
List fileArray = new ArrayList();
List fileTxt = new ArrayList();
List<String> newDoc = new ArrayList<String>();
while((fileName = fileRead.readLine()) !=null){
fileArray.add(fileName);
}
fileRead.close();
while((txtName = txtRead.readLine()) !=null){
fileTxt.add(txtName);
}
txtRead.close();
I want to compare fileArray data with fileTxt data, but don't know how to do that, because to I'm thinking to compare I need to get the data first. And to do that I need to looping the array and using the .get like
for(int a=0;a<fileTxt.size();a++){
System.out.println(fileTxt.get(a));
}
I know this is wrong, but anyone can help me.
note: I want to use something like contains method but can't because the data is 5 million rows. (not equals method)
Updated: I want to find a word in fileTxt that appeared in the fileArray. (so basically its like contains)
To compare 2 values in your 2 arraylists, you do this:
if(fileArray.get(index).equals(fileTxt.get(index)))
There is a wondefull function.
System.out.println(array1.equals(array2));
Then, you might want to check your answer by hands:
ArrayList like1 = new ArrayList();
ArrayList like2 = new ArrayList();
...
boolean flag = true;
if (!Math.min(like1.size(), like2.size()) == Math.max(like1.size(), like2.size()))
{
flag = false;
}
for (int i = 0; i < Math.min(like1.size(), like2.size()); i++) {
if (!like1.get(i).equals(like2.get(i))) {
flag = false;
break;
}
}
You can do this using the removeAll() method.
fileArray.removeAll(fileTxt);
fileTxt.removeAll(fileArray);
If one of them still have data, this means that the two List where different.
But storing 5 millions data in a Java list is not something I will advise you. Perhaps you should think about something else.
I have the below three elements :
play_full_NAME=556677
pause_full_NAME=9922
stop_full_NAME=112233
A string "abc" returns all the above three elements one by one from a particular piece of code.
I am trying to add all three elements in a list separated by a colon ":"
Sample output :
play_full_NAME=556677:pause_full_NAME=9922:stop_full_NAME=112233
My attempt:
List<String> list = new ArrayList<String>();
list.join(":",abc)
Please help with a better way to handle this.
Your understanding about List is little flawed. Comma is only printed for representation purposes.
To join strings with colon, you can do the following
List<String> list = Arrays.asList("play_full_NAME=556677",
"pause_full_NAME=9922",
"stop_full_NAME=112233");
String joinedString = String.join(":", list);
Did you really understood the List well?
In fact, there is no separator, each item / value is stored as different "object".
So you have some amount of independent values- Strings in this case, what can you see on screenshot bellow, or if you will do System.out.println(someList); it will call override of method toString() which is inherited from Object class , which is root parent class of all classes in Java.
So its absolutely nonsense to add some split character between each items in List, they are split already, you can access each item by get(int position) method.
So if you want to print each item of list "by yourself", can be done like follows:
for (int i = 0; i < someList.size(); i++) {
System.out.println(i + " = " + someList.get(i));
}
/* output will be
1 = 1 item
2 = 2 item
3 = 3 item
4 = 4 item
*/
If you want to implement custom method for printing "your list" then you can extend eg. ArrayList class and override toString method, but better and more trivial approach will be prepare some method in some utils to get formatted String output with context of List- eg. (notice there will be ; after last element)
public static String getFormatStringFromList(ArrayList<String> data) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.size(); i++) {
sb.append(data.get(i) + ";");
}
return sb.toString();
//eg. 0 item;1 item;2 item;3 item;4 item;
}
To avoid last separator you can do eg. simple check
public static String getFormatStringFromListWitoutLastSeparator(List<String> someList) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < someList.size(); i++) {
sb.append(someList.get(i));
if(i < someList.size() -1) {
sb.append(";");
}
}
return sb.toString();
//0 item;1 item;2 item;3 item;4 item
/*
someList[0] = 0 item
someList[1] = ;
someList[2] = 1 item
someList[3] = ;
{etc..}
*/
}
The best approach to get String from list will be like #krisnik advised:
String joinedString = String.join(":", list);
You would need to add the colon elements separately if you want them to be within your list.
For example:
List<String> list = new ArrayList<String>();
list.add(abc);
list.add(":");
list.add(def);
list.add(":");
and so on.
I would recommend against this, however, as you can simply format the output string using String.format or a StringBuilder when you need it.
Is it possible to add a wildcard to a string in a list in Java?
I have a string, which has different endings (for example: Key(1), Key(2), Key(3), Key(4), Key(5) etc etc.)
Is it possible to somehow add a string to a list, with a wildcard, so I could just do something like:
list.add("Key*wildcard*");
And it would have all the different endings of the string?
Many thanks :-)
EDIT:
This is how I'll use it.
I'm coding something for a game, which has to check for a specific item. This item has charges, which defines the ending of the name of the item. The item is called "Games Necklace".
Now, I want to check, if the user has the item, and if not, it will buy one. I have a list of items required to do a certain task, but the Games Necklace changes name (from 8-1, so it can be either "Games Necklace(8), Games Necklace(7), Games Necklace(6) and down to 1). I want to check if the users has all the items in the list of items needed, but it should return true, if the user has any version of the necklace
You can add a wildcard string to the list, but then you have to implement the search in the list yourself, and you can't rely on contains to work for you, as it simply calls the equals method, and equals would not do what you need.
Here is a possible solution:
Instead of using a List, use a List, and define the item as a regular expression.
List<Pattern> requiredList = new List<>();
requiredList.add(Pattern.compile("Sword");
requiredList.add(Pattern.compile("Games Necklace\\(\\d+\\)");
Write a method that matches all the patterns in the list against another collection. e.g.
public static hasAll( List<Pattern> required, Collection<String> available) {
for ( Pattern pat : available ) {
boolean matched = false;
for ( String item : needed ) {
if ( pat.matcher(item).matches() ) {
matched = true;
break;
}
}
if ( ! matched ) {
return false;
}
}
return true;
}
Another option is to define your game items in their own class, not as strings. That class will have a "type" and a "display name". And you'll check it in the list using the type, which will be "Games Necklace" (for all of them), and display using the display name.
No, as it doesn't make sense for a String to have multiple values (in Java at least). You could do it by making a class that represents your "multi-string" (of course change the mechanics oif it to fit your exact needs.
class MultiString {
List<String> strings = new ArrayList<String>();
public MultiString(String, prefix, int numValues) {
for(int i = 0; i < numValues; i++) strings.add(prefix + String.valueOf(i));
}
public String get(int i) {
return strings.get(i);
}
}
Or you could just add several values to the list.
public void addStrings(List<String> list, String prefix, int numValues) {
for(int i = 0; i < numValues; i++) list.add(prefix + String.valueOf(i));
}
More specific solutions can't be given until we know your exact needs.
List<String> list = new ArrayList<>();
for (int i= 8; i>0;i--){
list.add("Games Necklace("+i+")");
}
I have a list with some strings in it:
GS_456.java
GS_456_V1.java
GS_456_V2.java
GS_460.java
GS_460_V1.java
And it goes on. I want a list with the strings with the highest value:
GS_456_V2.java
GS_460_V1.java
.
.
.
I'm only thinking of using lots of for statements...but isn't there a more pratical way? I'd like to avoid using too many for statements...since i'm using them a lot when i execute some queries...
EDIT: The strings with the V1, V2,.... are the names of recent classes created. When someone creates a new version of GS_456 for example, they'll do it and add its version at the end of the name.
So, GS_456_V2 is the most recent version of the GS_456 java class. And it goes on.
Thanks in advance.
You will want to process the file names in two steps.
Step 1: split the list into sublists, with one sublist per file name (ignoring suffix).
Here is an example that splits the list into a Map:
private static Map> nameMap = new HashMap>();
private static void splitEmUp(final List names)
{
for (String current : names)
{
List listaly;
String[] splitaly = current.split("_|\\.");
listaly = nameMap.get(splitaly[1]);
if (listaly == null)
{
listaly = new LinkedList();
nameMap.put(splitaly[1], listaly);
}
listaly.add(current);
}
Step 2: find the highest prefix for each name. Here is an example:
private static List findEmAll()
{
List returnValue = new LinkedList();
Set keySet = nameMap.keySet();
for (String key : keySet)
{
List listaly = nameMap.get(key);
String highValue = null;
if (listaly.size() == 1)
{
highValue = listaly.get(0);
}
else
{
int highVersion = 0;
for (String name : listaly)
{
String[] versions = name.split("_V|\\.");
if (versions.length == 3)
{
int versionNumber = Integer.parseInt(versions[1]);
if (versionNumber > highVersion)
{
highValue = name;
highVersion = versionNumber;
}
}
}
}
returnValue.add(highValue);
}
return returnValue;
}
I guess you don't want simply the lexicographic order (the solution would be obvious).
First, remove the ".java" part and split your string on the character "_".
int dotIndex = string.indexOf(".");
String []parts = split.substring(0, dotIndex).split("_");
You are interested in parts[1] and parts[2]. The first is easy, it's just a number.
int fileNumber = Integer.parseInt(parts[1]);
The second one is always of the form "VX" with X being a number. But this part may not exist (if it's the base version of the file). In which case we can say that version is 0.
int versionNumber = parts.length < 2 ? 0 : Integer.parseInt(parts[2].substring(1));
Now you can compare based on these two numbers.
To make things simple, build a class FileIdentifier based on this:
class FileIdentifier {
int fileNumber;
int versionNumber;
}
Then a function that create a FileIdentifier from a file name, with logic based on what I explained earlier.
FileIdentifier getFileIdentifierFromFileName(String filename){ /* .... */ }
Then you make a comparator on String, in which you get the FileIdentifier for the two strings and compare upon FileIdentifier members.
Then, to get the string with "the highest value", you simply put all your strings in a list, and use Collections.sort, providing the comparator.
I need to create an Arraylist in a while loop with a name based on variables also in the loop. Here's what I have:
while(myScanner.hasNextInt()){
int truster = myScanner.nextInt();
int trustee = myScanner.nextInt();
int i = 1;
String j = Integer.toString(i);
String listname = truster + j;
if(listname.isEmpty()) {
ArrayList listname = new ArrayList();
} else {}
listname.add(truster);
i++;
}
The variable truster will show up more than once while being scanned, so the if statement is attempting to check if the arraylist already exists. I think I might have done that out of order, though.
Thanks for your help!
Store the ArrayLists in a Map:
Map<String, List<String> listMap = new HashMap<String,List<String>>();
while (myScanner.hasNextInt()){
// Stuff
List<String> list = new ArrayList<String>();
list.add(truster);
listMap.put(listname, list);
}
Note the use of generics (the bits in <>) to define the type of Object the List and Map can contain.
You can access the values stored in the Map using listMap.get(listname);
If I understand you correctly, create a list of lists or, better yet, create a map in which the key is the dynamic name you want and the value is the newly created list. Wrap this in another method and call it like createNewList("name").
Really not sure what you mean at all but you have some serious fundamental flaws with your code so I'll address those.
//We can define variables outside a while loop
//and use those inside the loop so lets do that
Map trusterMap = new HashMap<String,ArrayList<String>>();
//i is not a "good" variable name,
//since it doesn't explain it's purpose
Int count = 0;
while(myScanner.hasNextInt()) {
//Get the truster and trustee
Int truster = myScanner.nextInt();
Int trustee = myScanner.nextInt();
//Originally you had:
// String listname = truster + i;
//I assume you meant something else here
//since the listname variable is already used
//Add the truster concated with the count to the array
//Note: when using + if the left element is a string
//then the right element will get autoboxed to a string
//Having read your comments using a HashMap is the best way to do this.
ArrayList<String> listname = new ArrayList<String>();
listname.add(truster);
trusterMap.put(truster + count, listname);
i++;
}
Further, you are storing in myScanner a stream of Ints that will get fed in to the array, but which each have very different meanings (truster and trustee). Are you trying to read these in from a file, or user input? There are better ways of handling this and if you comment below with what you mean I'll update with a suggested solution.