I have two different string String A="example"; String B="example";
if concat both the string i am getting examplexample. Is there any possibility to avoid repetition of string with same name..??
How about this ?
if(!a.equals(b)){// or if needed use contains() , equalIgnoreCase() depending on your need
//concat
}
The Strings are not different, the same String object is assigned to two different variables ("two pointers to the same memory address").
Consider dumping all strings to a Set before concatenating, this avoids duplicates in the concatenated sequence:
Set<String> strings = new HashSet<String>();
StringBuilder resultBuilder = new StringBuilder();
for (String s:getAllStrings()) { // some magic to get all your strings
if (strings.contains(s))
continue; // has been added already
resultBuilder.append(s); // concatenate
strings.add(s); // put string to set
}
String result = resultBuilder.toString();
You can. Try something like this
private String concatStringExample1(String firstString, String secondString) {
if(firstString.equalsIgnoreCase(secondString)) { // String matched
return firstString; // or return secondString
} else { // Not matched
return firstString.concat(secondString);
}
}
or
private String concatStringExample2(String firstString, String secondString) {
if(firstString != null && firstString != null ) {
if(firstString.toLowerCase().indexOf(secondString.toLowerCase()) >= 0)
return firstString;
else if(secondString.toLowerCase().indexOf(firstString.toLowerCase()) >= 0)
return secondString;
else
return firstString.concat(secondString);
} else {
return "";
}
}
Just create a Set (It has mathematics set behaviour, it won't accept the duplicate objects)
Set<String> strings = new HashSet<String>();
//Fill this set with all the String objects
strings.add(A)
Strings.add(B)
//Now iterate this set and create a String Object
StringBuilder resultBuilder = new StringBuilder();
for(String string:Strings){
resultBuilder.append(string);
}
return resultBuilder.toString()
`
Related
I have an array of Strings:
String[] myArrayString = ...
It may contain elements or be null. I wrote the following method:
String myName = "";
if(myArrayString != null) {
List<String> temp = new ArrayList<>();
for(String tagID : myArrayString) {
Tag tag = tagManager.resolve(tagID);
if (tag != null) {
temp.add(resolveTagName(tag.getName()));
}
}
myName = temp.stream().map(Object::toString).collect(joining(" "));
myName = myName.substring(myName.lastIndexOf("/") + 1);
return myName;
}
I have a feeling it is not efficient enough and might be done in one single stream (or possibly two). Could you help me with that?
Your code can indeed be converted to use one single stream. The for loop simply transforms each element of the string array (map) and filters the null ones (filter), then performs another transformation (map):
String myName = "";
if(myArrayString != null) {
myName = Arrays.stream(myArrayString)
.map(tagManager::resolve)
.filter(Objects::nonNull)
.map(x -> resolveTagName(x.getName()))
.collect(joining(" "));
myName = myName.substring(myName.lastIndexOf("/") + 1);
return myName;
}
Also note that streams are not necessarily more efficient than a for loop, as it has some overheads as well. To measure performance, you use a profiler, not just by reading the code.
as it mentioned in the title, I have this code
String a = flett("AM ","L","GEDS","ORATKRR","","R TRTE","IO","TGAUU");
public static String flett(String... s){
StringBuilder merge = new StringBuilder();
for (int i = 0; i < s.length; i++) {
merge.append(s.charAt(i));
}
return merge;
}
I got an error at chartAt(i) ?
how for example I can call every character in the array s and save them into merge or call an specific character like the first character from each one and save them into merge ?
s[i].charAt(j);
where i - the index of an array, j - the index of a letter within a String.
A Java 8 method that collects the first letter of each array's element might look like
public String flett(String... s) {
return Arrays.stream(s)
.map(i -> i.length() > 0 ? String.valueOf(i.charAt(0)) : "")
.collect(Collectors.joining());
}
For the array "AM ","L","GEDS","ORATKRR","","R TRTE","IO","TGAUU", it results in "ALGORIT".
You have to use a variable amount of String parameters, then concatenate all first characters of non empty Strings of the parameters and return the concatenated object:
public static void main(String[] args) {
String s = flett("AM ","L","GEDS","ORATKRR","","R TRTE","IO","TGAUU", "HOLA", "MMMMH");
System.out.println(s);
}
// Please note the parameter, it takes a various amount of Strings
public static String flett(String ... values) {
// create something that concatenates Strings (other options possible)
StringBuilder sb = new StringBuilder();
// the parameters are now an array of Strings, which you can "foreach"
for (String s : values) {
// check for empty ones and skip those
if (!s.equals("")) {
// append the first character of a valid parameter
sb.append(s.charAt(0));
}
}
return sb.toString();
}
Be surprised by the output…
This method get some Strings and Create String from the first character of each String.
public static String flett(String... s) {
StringBuilder res = new StringBuilder(s.length);
for (String a : s) {
if (!a.isEmpty()) {
res.append(a.charAt(0));
}
}
return res.toString();
}
Consider a code:
URI one = URI.create("http://localhost:8081/contextRoot/main.html?one=1&second=2");
URI second = URI.create("http://localhost:8081/contextRoot/main.html?second=2&one=1");
System.out.println(one.equals(second));
And it prints false. Is there a way to test URI without URI parameters order?
Unforunately, equals methods of URI/URL objects are not always do, what you are exactly waiting for. That is why, to compare 2 URI with different parameters order (if you think, the order is not important for you), you should use some utility logic. For example, as follows:
public static void main(String... args) {
URI one = URI.create("http://localhost:8081/contextRoot/main.html?one=1&second=2");
URI second = URI.create("http://localhost:8081/contextRoot/main.html?second=2&one=1");
System.out.println(one.equals(second));
System.out.println(areEquals(one, second));
}
private static boolean areEquals(URI url1, URI url2) {
//compare the commons part of URI
if (!url1.getScheme().equals(url1.getScheme()) ||
!url1.getAuthority().equals(url2.getAuthority()) ||
url1.getPort() != url2.getPort() ||
!url1.getHost().equals(url2.getHost())) {
return false;
}
//extract query parameters
String params1 = url1.getQuery();
String params2 = url2.getQuery();
if ((params1 != null && params2 != null) && (params1.length() == params2.length())) {
//get sorted list of parameters
List<String> list1 = extractParameters(params1);
List<String> list2 = extractParameters(params2);
//since list are sorted and contain String objects,
//we can compare the lists objects
return list1.equals(list2);
} else {
return false;
}
}
//return sorted list of parameters with the values
private static List<String> extractParameters(String paramsString) {
List<String> parameters = new ArrayList<>();
String[] paramAr = paramsString.split("&");
for (String parameter : paramAr) {
parameters.add(parameter);
}
Collections.sort(parameters);
return parameters;
}
I wish you can help me I want to do is I have two variables of type string
String text = "HELLO HOW ARE YOU";
String value = "abc";
I want to do is see if any character of the variable values in text and contains tested but I only detects a single character but not
if(text.toUpperCase().contains(value.toUpperCase()))throw new Exception("NOT LETTERS");
You could use the List API...
String text = "HELLO HOW ARE YOU";
String value = "abc";
List<String> left = new ArrayList<>(Arrays.asList(text.toUpperCase().split("")));
List<String> right = new ArrayList<>(Arrays.asList(value.toUpperCase().split("")));
boolean hasAny = left.removeAll(right);
Basically this creates a List of each word then removes all the matches from the second in the first. A return value of true means the first List was modified, meaning it had matching values. You might even be able to compare the difference in size to determine how many matches there were.
You could also use Java 8's Stream API...
String text = "HELLO HOW ARE YOU";
String value = "abc";
List<String> left = new ArrayList<>(Arrays.asList(text.toUpperCase().split("")));
List<String> right = new ArrayList<>(Arrays.asList(value.toUpperCase().split("")));
boolean anyMatch = left.stream().anyMatch((String t) -> {
return right.contains(t);
});
Again, this will simply return true if the first List contains ANY of the values in the second List
Now, if you wanted to know which values actually matched, you might be able to use something like...
Set<String> collect = right.stream().filter((String t) -> {
return left.contains(t);
}).collect(Collectors.toSet());
System.out.println(collect);
Which in you example, would print
[A]
You can try like this:
public static boolean findLetters() {
String text = "HELLO HOW ARE YOU";
String value = "abc";
for (int i = 0; i < value.length(); i++) {
if (text.indexOf(value.toUpperCase().charAt(i)) == -1) {
return false;
}
}
return true;
}
Not sure if I understand the question quite well, but you may try this:
String text = "HELLO HOW ARE YOU";
String value = "abc";
for(char c : value.toUpperCase().toCharArray()) {
if (text.indexOf(c) != -1) {
throw new Exception("NOT LETTERS");
}
}
Consider the following String :
5|12345|value1|value2|value3|value4+5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4+
Here is how I want to split string, split it with + so I get this result :
myArray[0] = "5|12345|value1|value2|value3|value4";
myArray[1] = "5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4";
if string has doesn't contain char "?" split it with "|" and continue to part II, if string does contain "?" split it and for each part split it with "|" and continue to part II.
Here is part II :
myObject.setAttribute1(newString[0]);
...
myObject.setAttribute4(newString[3]);
Here what I've got so far :
private static String input = "5|12345|value1|value2|value3|value4+5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4+";
public void mapObject(String input){
String[] myArray = null;
if (input.contains("+")) {
myArray = input.split("+");
} else {
myArray = new String[1];
myArray[0] = input;
}
for (int i = 0; i < myArray.length; i++) {
String[] secondaryArray = null;
String[] myObjectAttribute = null;
if (myArray[i].contains("?")) {
secondaryArray = temporaryString.myArray[i].split("?");
for (String string : secondaryArray) {
myObjectAttribute = string.split("\\|");
}
} else {
myObjectAttribute = myArray[i].toString().split("\\|");
}
myObject.setAttribute1(myObjectAttribute[0]);
...
myObject.setAttribute4(myObjectAttribute[3]);
System.out.println(myObject.toString());
}
Problem :
When I split myArray, going trough for with myArray[0], everything set up nice as it should.
Then comes the myArray[1], its split into two parts then the second part overrides the value of the first(how do I know that?). I've overridden toString() method of myObject, when I finish I print the set values so I know that it overrides it, does anybody know how can I fix this?
I'm not quite sure what the intention is here, but in this snippet of code
secondaryArray = temporaryString.split("?");
for (String string : secondaryArray) {
myObjectAttribute = string.split("\\|");
}
if secondaryArray has two elements after the split operation, you are iterating over each half and re-assigning myObjectAttribute to the output of string.split("\|") each time. It doesn't matter what is in the first element of secondaryArray, as after this code runs myObjectAttribute is going to contain the result of split("\\|") on the last element in the array.
Also, there is no point in calling .toString() on a String object as you do in temporaryString = myArray[i].toString().
The code doesn't seem to be able to handle the possible expansion of strings in the secondary case. To make the code clearer, I would use a List rather than array.
private static String input = "5|12345|value1|value2|value3|value4+5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4+";
private void split(List<String> input, List<String> output, String split) {
for (String s: input) {
if (s.contains(split))
{
output.addAll(Arrays.asList(s.split(Pattern.quote(split)));
}
else
output.add(s);
}
}
public void mapObject(String input) {
List<String> inputSrings = new ArrayList<String>();
List<String> splitPlus = new ArrayList<String>();
inputStrings.add(input);
split(inputStrings, splitPlus);
List<String> splitQuest = new ArrayList<String>();
split(splitPlus, splitQuest, "?");
for (String s: splitQuest) {
// you can now set the attributes from the values in the list
// splitPipe
String[] attributes = s.split("\\|");
myObject.setAttribute1(attributes[0]);
....
myObject.setAttribute4(attributes[3]);
System.out.println(myObject);
}
}