I have a list of strings say "abc" "bcd" "xyz" etc
and a string "xyzxxxxxxxxx" and i need to find whether any of the list value is present in the string.
in C# we have .any function to find it . Is there any way in java??
I don't think it is possible in 1 line, but you can loop over the list and use .contains()
String[] listOfString = { "abc", "bcd", "xyz" };
String s = "xyzxxxxxxxxx";
for (String temp : listOfStrings) {
s.contains(temp);
}
You can also use indexOf() if you want to know the position of the occurrence.
You can look for a presence of a substring within a larger string by using the String.contains method:
String needle = "abc";
String haystack = "xyzxxxxxxxxx";
if (haystack.contains(needle)) {
// react accordingly
}
To expand that to your specific requirement, you can simply loop over all of your substrings and check each of them in turn. (Possibly short-circuiting early depending on what you want to do in that case where a match is found).
public class Main {
public static void main(String[] args) {
String[] strings = new String[]{"abc", "dfg"};
String ss = "abcd";
for(String s : strings) {
System.out.println(ss + " contains " + s + ": " + ss.contains(s));
}
}
}
This is an example that would do what you are trying to achieve:
public static void main(String[] args) {
List<String> list = Arrays.asList("abc","bcd", "xyz");
String search = "xyzxxxxxxxxx";
for (String s : list) {
if (search.contains(s)) {
System.out.println("Found " + s + " in " + search);
}
}
}
You could use something like:
String source = "xyzxxxxxxxxx";
List<String> strings = ...;
for (int i = 0; i < string.size();i++)
{
if (source.contains(strings.get(i))
{
System.out.println("Match found at " + (i + 1));
break;
}
}
Loop through your list and use
C# String.IndexOf
Java String.indexOf
you could iterate over the list, and call string.contains(listelement) everytime.
Related
I am struggling with removing spaces in an arraylist of strings.
Say the user input is as follows: "I walked my dog", my code outputs this:
[I, walked, my, dog]
I want it to have no spaces as such:
[I,walked,my,dog]
I tried to remove whitespace on each individual string before I add it to the arrayList, but the output still has the spaces.
Scanner input = new Scanner(System.in);
ArrayList<String> userWords = new ArrayList<String>();
ArrayList<String> SplituserWords = new ArrayList<String>();
System.out.println("Please enter your phrase: ");
userWords.add(input.nextLine());
for (int index = 0; index < userWords.size(); index++) {
String[] split = userWords.get(index).split("\\s+");
for (String word : split) {
word.replaceAll("\\s+","");
SplituserWords.add(word);
}
System.out.println(SplituserWords);
I suggest just taking advantage of the built-in Arrays#toString() method here:
String words = input.nextLine();
String output = Arrays.toString(words.split(" ")).replace(" ", "");
System.out.println(output); // [I,walked,my,dog]
When you are writing System.out.println(SplituserWords);, you are implicitly calling ArrayList#toString() which generates the list's string and that includes spaces after commas.
You can instead generates your own string output, for example with:
System.out.println("[" + String.join(",", SplituserWords) + "]");
If you insist on using List, it will do it for you.
String input = "I walked my dog";
List<String> SplitUserWords = Arrays.asList(input.split(" "));
String output = SplitUserWords.toString().replace(" ", "");
System.out.println(output); //[I,walked,my,dog]
I tried to remove whitespace on each individual string before I add it to the arrayList, but the output still has the spaces.
That won't work because that isn't the problem. The issue is that it is the list implementation that formats the output for you inserts a space after each comma. It does this in the toString() method. To avoid having to explicitly call replace each time you can also do it like this by overidding toString() when you create your List.
List<String> myList = new ArrayList<>(List.of("I","walked","my", "dog")) {
#Override
public String toString() {
// use super to call the overidden method to format the string
// then remove the spaces and return the new String
return super.toString().replace(" ", "");
}
};
System.out.println(myList);
myList.addAll(List.of("and", "then","fed", "my", "cat"));
System.out.println(myList);
prints
[I,walked,my,dog]
[I,walked,my,dog,and,then,fed,my,cat]
You can also subclass ArrayList as follows. Here I have added the three constructors that ArrayList implements. Note that is is a somewhat extreme solution and may not be worth it for occasionally reformatting of the output. I included it for your consideration.
class MyArrayList<E> extends ArrayList<E> {
public MyArrayList() {
super();
}
public MyArrayList(int capacity) {
super(capacity);
}
public MyArrayList(Collection<? extends E> c) {
super(c);
}
#Override
public String toString() {
return super.toString().replace(" ", "");
}
}
And it would work like so.
MyArrayList<String> myList = new MyArrayList<>(List.of("This", "is", "a","test."));
System.out.println(myList);
prints
[This,is,a,test.]
I want the Java code for converting an array of strings into an string.
Java 8+
Use String.join():
String str = String.join(",", arr);
Note that arr can also be any Iterable (such as a list), not just an array.
If you have a Stream, you can use the joining collector:
Stream.of("a", "b", "c")
.collect(Collectors.joining(","))
Legacy (Java 7 and earlier)
StringBuilder builder = new StringBuilder();
for(String s : arr) {
builder.append(s);
}
String str = builder.toString();
Alternatively, if you just want a "debug-style" dump of an array:
String str = Arrays.toString(arr);
Note that if you're really legacy (Java 1.4 and earlier) you'll need to replace StringBuilder there with StringBuffer.
Android
Use TextUtils.join():
String str = TextUtils.join(",", arr);
General notes
You can modify all the above examples depending on what characters, if any, you want in between strings.
DON'T use a string and just append to it with += in a loop like some of the answers show here. This sends the GC through the roof because you're creating and throwing away as many string objects as you have items in your array. For small arrays you might not really notice the difference, but for large ones it can be orders of magnitude slower.
Use Apache commons StringUtils.join(). It takes an array, as a parameter (and also has overloads for Iterable and Iterator parameters) and calls toString() on each element (if it is not null) to get each elements string representation. Each elements string representation is then joined into one string with a separator in between if one is specified:
String joinedString = StringUtils.join(new Object[]{"a", "b", 1}, "-");
System.out.println(joinedString);
Produces:
a-b-1
I like using Google's Guava Joiner for this, e.g.:
Joiner.on(", ").skipNulls().join("Harry", null, "Ron", "Hermione");
would produce the same String as:
new String("Harry, Ron, Hermione");
ETA: Java 8 has similar support now:
String.join(", ", "Harry", "Ron", "Hermione");
Can't see support for skipping null values, but that's easily worked around.
From Java 8, the simplest way I think is:
String[] array = { "cat", "mouse" };
String delimiter = "";
String result = String.join(delimiter, array);
This way you can choose an arbitrary delimiter.
You could do this, given an array a of primitive type:
StringBuffer result = new StringBuffer();
for (int i = 0; i < a.length; i++) {
result.append( a[i] );
//result.append( optional separator );
}
String mynewstring = result.toString();
Try the Arrays.deepToString method.
Returns a string representation of the "deep contents" of the specified
array. If the array contains other arrays as elements, the string
representation contains their contents and so on. This method is
designed for converting multidimensional arrays to strings
Try the Arrays.toString overloaded methods.
Or else, try this below generic implementation:
public static void main(String... args) throws Exception {
String[] array = {"ABC", "XYZ", "PQR"};
System.out.println(new Test().join(array, ", "));
}
public <T> String join(T[] array, String cement) {
StringBuilder builder = new StringBuilder();
if(array == null || array.length == 0) {
return null;
}
for (T t : array) {
builder.append(t).append(cement);
}
builder.delete(builder.length() - cement.length(), builder.length());
return builder.toString();
}
public class ArrayToString
{
public static void main(String[] args)
{
String[] strArray = new String[]{"Java", "PHP", ".NET", "PERL", "C", "COBOL"};
String newString = Arrays.toString(strArray);
newString = newString.substring(1, newString.length()-1);
System.out.println("New New String: " + newString);
}
}
You want code which produce string from arrayList,
Iterate through all elements in list and add it to your String result
you can do this in 2 ways: using String as result or StringBuffer/StringBuilder.
Example:
String result = "";
for (String s : list) {
result += s;
}
...but this isn't good practice because of performance reason. Better is using StringBuffer (threads safe) or StringBuilder which are more appropriate to adding Strings
String[] strings = new String[25000];
for (int i = 0; i < 25000; i++) strings[i] = '1234567';
String result;
result = "";
for (String s : strings) result += s;
//linear +: 5s
result = "";
for (String s : strings) result = result.concat(s);
//linear .concat: 2.5s
result = String.join("", strings);
//Java 8 .join: 3ms
Public String join(String delimiter, String[] s)
{
int ls = s.length;
switch (ls)
{
case 0: return "";
case 1: return s[0];
case 2: return s[0].concat(delimiter).concat(s[1]);
default:
int l1 = ls / 2;
String[] s1 = Arrays.copyOfRange(s, 0, l1);
String[] s2 = Arrays.copyOfRange(s, l1, ls);
return join(delimiter, s1).concat(delimiter).concat(join(delimiter, s2));
}
}
result = join("", strings);
// Divide&Conquer join: 7ms
If you don't have the choise but to use Java 6 or 7 then you should use Divide&Conquer join.
String array[]={"one","two"};
String s="";
for(int i=0;i<array.length;i++)
{
s=s+array[i];
}
System.out.print(s);
Use Apache Commons' StringUtils library's join method.
String[] stringArray = {"a","b","c"};
StringUtils.join(stringArray, ",");
When we use stream we do have more flexibility, like
map --> convert any array object to toString
filter --> remove when it is empty
join --> Adding joining character
//Deduplicate the comma character in the input string
String[] splits = input.split("\\s*,\\s*");
return Arrays.stream(splits).filter(StringUtils::isNotBlank).collect(Collectors.joining(", "));
If you know how much elements the array has, a simple way is doing this:
String appendedString = "" + array[0] + "" + array[1] + "" + array[2] + "" + array[3];
My Java routine should find a String from one ArrayList as a char sequence of another ArrayList String.
If I search for a String item from the source ArrayList in the target ArrayList it works.
If the target ArrayList item has more alphanumeric literals I tried to find the wanted part by using a char sequence.
Short Example in Words:
ArrayList_A Items: "A0B","C1D","E2F"
ArrayList_B Item: "A0B"
Result: Item B found in ArrayList_A Items (works)
ArrayList_A Items: "A0B/C1D","E2F"
ArrayList_B Item: "A0B"
Result: Item B found in ArrayList_A Items (this is what I want additionally)
Below is my partly working code. Can anyone please fix it so that I can learn from the solution?
import java.util.ArrayList;
public class Checking {
static void checkValues () {
ArrayList<String> arrayListA = new ArrayList();
arrayListA.add("A0B/C1D");
arrayListA.add("E2F");
System.out.println("\narrayListA: " + arrayListA);
int sizeLA = arrayListA.size();
System.out.println("arrayListA Length:" + sizeLA);
ArrayList<String> arrayListB = new ArrayList();
arrayListB.add("A0B");
arrayListB.add("E2F");
System.out.println("\narrayListB: " + arrayListB);
int sizeLB = arrayListB.size();
System.out.println("arrayListB Length:" + sizeLB);
ArrayList<String> arrayListFound = new ArrayList();
//Something must be fixed here...
arrayListB.stream().forEach((searchStr) -> {
System.out.print("\nstr Search Item is: " + searchStr);
if(arrayListA.contains((CharSequence)searchStr)){
System.out.print(" - found!" );
arrayListFound.add((String) searchStr);
}
else {
System.out.print(" - not found");
}
});
System.out.println("\n\narrayListFound Items: " + arrayListFound);
int sizeListFound = arrayListFound.size();
System.out.println("sizeListFound Length :" + sizeListFound);
System.out.println("Expected to be fully found in arrayListFound: " + arrayListB);
}
public static void main(String[] args) {
checkValues();
}
}
At first you should use functional style programming. forEach() doesn't allow you more than standard for (...)
For exact matching
ArrayList<String> arrayListFound = arrayListB.stream()
.filter(arrayListA::contains)
.collect(Collectors.toList());
For substring matcing
ArrayList<String> arrayListFound = arrayListB.stream()
.filter(itemB -> arrayListA.stream()
.matchAny(itemA -> itemA.contains(itemB))
)
.collect(Collectors.toList());
You may stream over both collections and use String#contains instead of List#contains.
It will add all the corresponding String objects from B contained in A to arrayListFound
arrayListB.stream().forEach(b ->
arrayListA.stream().forEach(a -> {
if (a.contains(b)){
arrayListFound.add(b);
}
}
));
if(arrayListA.contains((CharSequence)searchStr)){
System.out.print(" - found!" );
arrayListFound.add((String) searchStr);
}
This snippet says, "if my list contains exactly this string, it's found". But your String A0B, isn't the same as A0B/C1D. Iterating over both lists and checking the contains method of String and not of ArrayList, you'll find what you need. E.g:
arrayListB.stream().forEach((searchStr) -> {
System.out.print("\nstr Search Item is: " + searchStr);
arrayListA.stream().forEach((sndStr) -> {
if (sndStr.contains(searchStr) || searchStr.contains(sndStr)) {
System.out.print(" - found!");
arrayListFound.add((String) searchStr);
} else {
System.out.print(" - not found");
}
});
});
An alternative solution that only slightly modifies your implementation is as follows.
arrayListB.stream().forEach((searchStr) -> {
if(arrayListA.stream().anyMatch(str -> str.contains((CharSequence)searchStr))){
System.out.print(" - found!" );
arrayListFound.add((String) searchStr);
}
else {
System.out.print(" - not found");
}
});
i. We can use anyMatch which would be perform better than foreach.
ii. Here we are checking if there exists any string in arrayListA which would have searchStr from arrayListB as the sub-string.
To do it in purely functional style without mutating the arrayListFound list, the following approach can be adopted:
Predicate<String> isInArrayA = searchStr-> arrayListA.stream().anyMatch(str -> str.contains(searchStr));
arrayListFound = (ArrayList<String>) arrayListB.stream()
.filter(isInArrayA)
.collect(Collectors.toList());
I have the following method which is passed a HashSet<String> of words from IMDB reviews.
private static void reduceVocab(HashSet<String> vocab) {
for (Iterator<String> i = vocab.iterator(); i.hasNext();) {
String element = i.next();
element = element.replaceAll("[^a-zA-Z0-9]", ""); // Need to replace this
if (element.length() <= 3) {
i.remove();
}
}
}
I want to perform a couple of actions to reduce the size of the HashSet by removing Strings that are too short and removing non-alphanumeric characters. Is there any way to perform what I'm trying to do with element.replaceAll()?
You cannot add to a HashSet while iterating over it. This makes what you are trying to do slightly awkward. The line
element = element.replaceAll("[^a-zA-Z0-9]", "");
gives a new string, but the new string won't be in the set.
You can do it like this:
private static void reduceVocab(HashSet<String> vocab) {
Set<String> copy = new HashSet<>();
for (String str : vocab) {
str = str.replaceAll("[^a-zA-Z0-9]", "");
if (str.length() > 3)
copy.add(str);
}
vocab.clear();
vocab.addAll(copy);
}
I have an instance of ArrayList named array.
When I parse some JSON data it will store it all in array.
When I do a System.out.println(array); it will list a long list of items, around 30, but when I write System.out.println(array.size); it will give the value one.
How come it only gives me the value 1 when the list contains at least 30 values?
My code for this:
public void setLocationName (String name) {
array = new ArrayList<String>();
array.add(name);
System.out.println(array); //This return a long list
System.out.println(array.size()); //But this only return the value 1
}
public String[] getLocationName() {
String tArray[] = null;
for (int i = 0; i < array.size(); i++){
System.out.println(i);
tArray = array.toArray(new String[i]);
}
return tArray;
}
}
The long list :
[Brunnsparken, Göteborg]
[Brunnsgatan, Göteborg]
[Brunnslyckan, Lerum]
[Brunnsbotorget, Göteborg]
[Brunnsnäs, Ulricehamn]
[Brunnshult, Mellerud]
[Brunnsdal, Skövde]
[Brunns skola, Ulricehamn]
[Brunnsgården, Kungälv]
[Brunns kyrka, Ulricehamn]
[Boråsparken, Borås]
[Stadsparken, Ulricehamn]
[Lysekilsparken, Lysekil]
[Mössebergsparken, Falköping]
[Dalaborgsparken, Vänersborg]
[Rösparken, Åmål]
[Lillhagsparken Norra, Göteborg]
[Lillhagsparken Södra, Göteborg]
[Sylte Ryrbäcksparken, Trollhättan]
[Skogstomtsparken, Borås]
[Svinesundsparken, Norge]
[Håjumsparken, Trollhättan]
[Eriksdalsparken, Bollebygd]
[Fridhemsparken, Lidköping]
My result will be that only one item from the list will be returned in the tArray but I wanna return the whole list.
How to solve this?
Java doesn't understand Json and basically what you're doing is add a string to an array
this.array.add(name); ---> add one value to the array, therefore the size is just one
you may need to use a specific Json library to parse the data in to an java arraylist.
regards
Look like you need to parse the String into pairs.
Looks to me like a Map might be the most appropriate structure to store the data in - I presume the first part from the value is unique.
Regex is probably the best approach to parsing the data:
public static void main(String[] args) {
final String data = "[Brunnsparken, Göteborg]\n"
+ "[Brunnsgatan, Göteborg]\n"
+ "[Brunnslyckan, Lerum]\n"
+ "[Brunnsbotorget, Göteborg]\n"
+ "[Brunnsnäs, Ulricehamn]\n"
+ "[Brunnshult, Mellerud]\n"
+ "[Brunnsdal, Skövde]\n"
+ "[Brunns skola, Ulricehamn]\n"
+ "[Brunnsgården, Kungälv]\n"
+ "[Brunns kyrka, Ulricehamn]\n"
+ "[Boråsparken, Borås]\n"
+ "[Stadsparken, Ulricehamn]\n"
+ "[Lysekilsparken, Lysekil]\n"
+ "[Mössebergsparken, Falköping]\n"
+ "[Dalaborgsparken, Vänersborg]\n"
+ "[Rösparken, Åmål]\n"
+ "[Lillhagsparken Norra, Göteborg]\n"
+ "[Lillhagsparken Södra, Göteborg]\n"
+ "[Sylte Ryrbäcksparken, Trollhättan]\n"
+ "[Skogstomtsparken, Borås]\n"
+ "[Svinesundsparken, Norge]\n"
+ "[Håjumsparken, Trollhättan]\n"
+ "[Eriksdalsparken, Bollebygd]\n"
+ "[Fridhemsparken, Lidköping]";
final Pattern pattern = Pattern.compile("\\[([^,]++),\\s++([^\\]]++)\\]");
final Matcher matcher = pattern.matcher(data);
final Map<String, String> items = new TreeMap<>();
while (matcher.find()) {
items.put(matcher.group(1), matcher.group(2));
}
for (final Entry<String, String> entry : items.entrySet()) {
System.out.println(entry);
}
}
Output from this:
Boråsparken=Borås
Brunns kyrka=Ulricehamn
Brunns skola=Ulricehamn
Brunnsbotorget=Göteborg
Brunnsdal=Skövde
Brunnsgatan=Göteborg
Brunnsgården=Kungälv
Brunnshult=Mellerud
Brunnslyckan=Lerum
Brunnsnäs=Ulricehamn
Brunnsparken=Göteborg
Dalaborgsparken=Vänersborg
Eriksdalsparken=Bollebygd
Fridhemsparken=Lidköping
Håjumsparken=Trollhättan
Lillhagsparken Norra=Göteborg
Lillhagsparken Södra=Göteborg
Lysekilsparken=Lysekil
Mössebergsparken=Falköping
Rösparken=Åmål
Skogstomtsparken=Borås
Stadsparken=Ulricehamn
Svinesundsparken=Norge
Sylte Ryrbäcksparken=Trollhättan
You can the access the items by looping (as above) or by getting values from the Map by key. The TreeMap I have used will sort the data by key, you can also use a LinkedHashMap to store the data in insertion order.
You could also store the items in a List of tuple like structures.
public void setLocationName (String name) {
array = new ArrayList<String>();
array.add(name);
System.out.println(array); //This return a long list
System.out.println(array.size()); //But this only return the value 1
}
You are creating a new ArrayList each time you call this method:
array = new ArrayList<String>();
You could just remove the above line, however I suggest you rename the method as this is no longer a setter and you are in fact now adding to an existing list each time you call this method.
I suggest what you want to do is build your List before parsing to the setter, perhaps using a foreach loop (I'm not sure what kind of object you are working with) and simplify your setter (setLocationName) to accomodate.
So it would become:
public void setLocationName(ArrayList<String> names)
{
this.array = names;
System.out.println(array); //This return a long list
System.out.println(array.size()); //But this only return the value 1
}