Check starts-with for each element in array - java

Is there any utility function in java which does String.startsWith for each element in string array?
For eg:
String[] s = {"ABC", "BBV", "ABCD", "NBHH"};
Is there any way to do :
array.startsWith("AB");
Returns ABC and ABCD

You can use the stream API:
String[] result =
Arrays.stream(s)
.filter(a -> a.startsWith("AB"))
.toArray(String[]::new);

If you are using Java 8, you can use filter like this :
String[] result = Stream.of(s).filter(a -> a.startsWith("AB")).toArray(String[]::new);
If you want to return a List you can use :
List<String> rst = Stream.of(s).filter(a->a.startsWith("AB")).collect(Collectors.toList());

You could use Stream if you're using Java 8. In case you aren't then you'd probably want to use the solution below:
String s[]={"ABC","BBV","ABCD","NBHH"};
for (String i : s) {
if (i.startsWith("AB")) { // startsWith() returns boolean
System.out.println(i);
}
}

Related

How to translate a lambda expression to normal code?

I was writing in java 1.8 and now I need to downgrade to 1.6. I have a problem writing this code in the normal way. Any suggestions?
return Stream.of(field.getText().split(","))
.map(String::trim)
.filter(s -> !s.isEmpty())**
.map(Integer::valueOf)
.collect(Collectors.toSet());
That is what I tried:
if(!splitted[i].isEmpty()) {
set.add(Integer.valueOf(splitted[i]));
}
Set<Integer> results = new HashSet<>();
for (String part : field.getText().split(",")) {
String trimmed = part.trim();
if (trimmed.isEmpty()) continue;
results.add(Integer.valueOf(trimmed));
}
Your code does the following:
split the text of field along ','
call trim() on each of these
only work on all those which are not empty
parse this Strings to Integers
put them in a Set
this could be done like this:
EDIT: for-each is nicer and can be used since java 1.5
Set<Integer> set = new HashSet<>();
for(String split : field.getText().split(",")) {
split = split.trim();
if(!split.isEmpty()) {
set.add(Integer.valueOf(split));
}
}

Which Algorithm should i use here? Finding Strings in a String Array

I have 2 Arrays.
One Array has Strings, which i look for.
static String[] namesToLookFor = { "NR", "STAFFELNR", "VONDATUM"};
the otherArray has Strings, which i got from a *.csv file.
indexString = indexReader.readLine();
indexArray = indexString.split(";");
My Goal is to system.out.println() the Values which are the indexArray[] and NOT in the namesToLookFor[].
For example:
namesToLookFor = {"NR"};
indexArray = {"HELLO","NR"};
//Any Algorithm here...
So in this case"HELLO" should be printed out, since it is NOT in the namesToLookFor[] Array.
If you are using java8 you can do the following
List<String> list = Arrays.asList(namesToLookFor);
Arrays.stream(indexArray)
.filter(item -> !list.contains(item))
.forEach(System.out::println);
You could iterate over your indexArray and check for each element if its contained in your namesToLookFor Array:
String[] namesToLookFor = {"NR"};
String[] indexArray = {"HELLO","NR"};
List<String> excludedNames = Arrays.asList(namesToLookFor);
for(String s : indexArray) {
if (!excludedNames.contains(s)) {
System.out.println(s);
}
}
Will output only "HELLO".
// Put array into set for better performance
Set<String> namesToFilter = new HashSet<>(Arrays.asList("NR", "STAFFELNR"));
String[] indexArray = indexReader.readLine().split(";");
// Create list with unfiltered values and remove unwanted ones
List<String> resultList = new ArrayList<>(indexArray);
resultList.removeAll(namesToFilter);
// Do with result whatever you want
for (String s : resultList)
System.out.println(s);
With Array you can use contains function but after converting it to be ArrayList, the contains function will check if the ArrayList contains a specific value.
for (int i =0; i<indexArray.length; i++) {
if (!Arrays.asList(namesToLookFor).contains(indexArray[i]))
System.out.println(indexArray[i]);
}

Java Streams: Is there a cleaner way of doing this?

I am using streams to concatenate a series of strings and add commas between them, but there must be no comma at the beginning or the end of the result string.
import java.util.Arrays;
import java.util.List;
public class QuestionNine {
public static void main(String[] args) {
new QuestionNine().launch();
}
public void launch(){
List<String> words = Arrays.asList("Hello", "Bonjour", "engine", "Hurray", "What",
"Dog", "boat", "Egg", "Queen", "Soq", "Eet");
String result = (words.stream().map(str -> str + ",").reduce("", (a,b) -> a + b));
result = result.substring(0, result.length() -1); //removes last comma
System.out.println(result);
}
}
Instead of using the String.substring() method at the end to get rid of the last comma, is there a way i could have deleted the last comma within the stream pipeline?
The usual idiom is to use the joining Collector with Streams.
String res = words.stream().collect(Collectors.joining(","));
Although you can use String.join in your case since you are directly dealing with an Iterable.
String res = String.join(",", words);
The problem with your approach is that the mapping function you apply impose that there will be a comma at the end of each word. You could get rid of this mapping; and apply the reduce function such that you get the desired output:
.stream().reduce("", (a,b) -> a.isEmpty() ? b : a+","+b);
but I don't recommend this.
Yes, you can use Collectors.joining() here:
String joined = words.stream().collect(Collectors.joining(", "));
Or, also as noted from comments, you can use newly added String.join(CharSequence, Iterable) method.
String joined = String.join(", ", words);

Convert Comma Separated Values to List<Long>

Assume I have a set of numbers like 1,2,3,4,5,6,7 input as a single String. I would like to convert those numbers to a List of Long objects ie List<Long>.
Can anyone recommend the easiest method?
You mean something like this?
String numbers = "1,2,3,4,5,6,7";
List<Long> list = new ArrayList<Long>();
for (String s : numbers.split(","))
list.add(Long.parseLong(s));
System.out.println(list);
Since Java 8 you can rewrite it as
List<Long> list = Stream.of(numbers.split(","))
.map(Long::parseLong)
.collect(Collectors.toList());
Little shorter versions if you want to get List<String>
List<String> fixedSizeList = Arrays.asList(numbers.split(","));
List<String> resizableList = new ArrayList<>(fixedSizeList);
or one-liner
List<String> list = new ArrayList<>(Arrays.asList(numbers.split(",")));
Bonus info:
If your data may be in form like String data = "1, 2 , 3,4"; where comma is surrounded by some whitespaces, the split(",") will produce as result array like ["1", " 2 ", " 3", "4"].
As you see second and third element in that array contains those extra spaces: " 2 ", " 3" which would cause Long.parseLong to throw NumberFormatException (since space is not proper numerical value).
Solution here is either:
using String#trim on those individual elements before parsing like Long.parseLong(s.trim())
consuming those extra whitespace along , while splitting. To do that we can use split("\\s*,\\s*") where
\s (written as "\\s" in string literals) represents whitespace
* is quantifier representing zero or more
so "\\s*" represents zero or more whitespaces (in other words makes it optional)
Simple and handy solution using java-8 (for the sake of completion of the thread):
String str = "1,2,3,4,5,6,7";
List<Long> list = Arrays.stream(str.split(",")).map(Long::parseLong).collect(Collectors.toList());
System.out.println(list);
[1, 2, 3, 4, 5, 6, 7]
Even better, using Pattern.splitAsStream():
Pattern.compile(",").splitAsStream(str).map(Long::parseLong).collect(Collectors‌​.toList());
String input = "1,2,3,4,5,6,7";
String[] numbers = input.split("\\,");
List<Integer> result = new ArrayList<Integer>();
for(String number : numbers) {
try {
result.add(Integer.parseInt(number.trim()));
} catch(Exception e) {
// log about conversion error
}
}
You can use String.split() and Long.valueOf():
String numbers = "1,2,3,4,5,6,7";
List<Long> list = new ArrayList<Long>();
for (String s : numbers.split(","))
list.add(Long.valueOf(s));
System.out.println(list);
If you're not on java8 and don't want to use loops, then you can use Guava
List<Long> longValues = Lists.transform(Arrays.asList(numbersArray.split(",")), new Function<String, Long>() {
#Override
public Long apply(String input) {
return Long.parseLong(input.trim());
}
});
As others have mentioned for Java8 you can use Streams.
List<Long> numbers = Arrays.asList(numbersArray.split(","))
.stream()
.map(String::trim)
.map(Long::parseLong)
.collect(Collectors.toList());
I've used the following recently:
import static com.google.common.collect.ImmutableList.toImmutableList;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
...
final ImmutableList<Long> result = Splitter.on(",")
.trimResults()
.omitEmptyStrings()
.splitToStream(value)
.map(Long::valueOf)
.collect(toImmutableList());
This uses Splitter from Guava (to handle empty strings and whitespaces) and does
not use the surprising String.split().
I would use the excellent google's Guava library to do it. String.split can cause many troubles.
String numbers="1,2,3,4,5,6,7";
Iterable<String> splitIterator = Splitter.on(',').split(numbers);
List<String> list= Lists.newArrayList(splitIterator );

removing [ and ] from arraylist

I have to print the list values in the form of String. But I am held up with the [ and ] in the list. Here is my code.
List dbid=new ArrayList();
dbid.add(ar.getdbID());
String check=ar.getdbID().toString();
output for the above code :
[2, 3,4]
But I just need this:
2,3,4
There are no [ and ] "in the List". It's only the String representation (produced by toString()) that contains those characters. It's important to distinguish those two things.
I'd use a Guava Joiner:
Joiner.on(',').join(dbid);
Of you can manually implement it:
StringBuilder b = new StringBuilder();
Iterator<?> it = dbid.iterator();
while (it.hasNext()) {
b.append(it.next());
if (it.hasNext()) {
b.append(',');
}
}
String result = b.toString();
Apache StringUtils join method is very useful for this:
StringUtils.join(new String[] { "1", "2", "3"}, ",");
This will return the string "1,2,3"
I think it is better just to iterate through the list. Something like this will do the trick:
for(int i=0; i<yourList().size();i++){
out.println(yourList().get(i));
}
Like this:
StringBuilder sb = new StringBuilder();
Iterator it = dbid.iterator();
if(it.hasNext()){
sb.append(it.next());
while(it.hasNext()){
sb.append(',').append(it.next());
}
}
return sb.toString();
toString() function will merely convert the object into its String form. So it is printing the String array as a string in your case. That is why [ ] has come.
You will have to do the following to get your required result.
List dbid=new ArrayList();
dbid.add(ar.getdbID());
String[] checks=ar.getdbID();
for(String check:checks) {
System.out.print(check+" ");
}
System.out.print("\n");
Hope you understand the usage.
String pattern = "[\\[\\]]";
String result = yourstring.replaceAll(pattern, "");
This is the best option by far that I have tried and it worked for me.
"yourstring"in this case will be your string object.
You can use replace method of String class to remove those brackets or you can use regular expression also (i guess regex will be overkill in your case)

Categories

Resources