How to translate a lambda expression to normal code? - java

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));
}
}

Related

Java Stream - String replace if match using Streams?

I have if condition where I am checking for String equality, if they match I store them in Set. Then I am looping through Set to check if ENUM3 value is present, if yes I replace that particular string with value String Java . I am using Iterator to loop and check for equality. I am looking for same functionality with use of streams where
1. I can loop through Set
2. Check for String equality
3. If ENUM3 found then replace with Java
4. Save all the matched String
Here is my code
{
Set<String> only = new HashSet<String>();
Iterator<Mark> itr = Marks.iterator();
while (itr.hasNext()) {
Mark find = itr.next();
if (ENUM1.getData().equals(find.search())||ENUM3.getData().equals(find.search())) {
only.add(find.search());
only = only.stream()
.map(macro -> macro.equals(ENUM3.getData()) ? "Java" : macro).collect(Collectors.toSet());
}
}
}
Here is what I tried using Stream
only = only.stream()
.map(macro -> macro.equals(ENUM3.getData()) ? "Java" : macro)
.collect(Collectors.toSet());
This should perform your entire operation:
Set<String> only = Marks.stream()
.map(Mark::search)
.filter(mark -> ENUM1.getData().equals(mark)
|| ENUM2.getData().equals(mark)
|| ENUM3.getData().equals(mark))
.map(macro -> macro.equals(ENUM3.getData()) ? "Java" : macro)
.collect(Collectors.toSet());
You seem to be unnecessarily doing these 2 (both of which are avoided in the pipeline above)
iterating through only in each iteration to replace ENUM3.getData() with Java
repeatedly calling Mark.search()

How to remove \n in every Arraylist item

I extract some Data into a Arraylist. And in every Item there are several line breaks (\n) that I want to get rid of afterwards.
I´ve tried to do this:
public List<String> MemberIDList() {
// Getting the ArrayList
idList = listProjection.getIDListOfMembers();
for (int i = 0; idList.size() > i; i++) {
String item = idList.get(i);
item.replaceAll("\n", "");
}
return idList;
}
If I print that out on the console, it still contains all the line breaks:
The ID ...... (not null)
145
145
Thanks
EDIT: I also want to filter unnecessary whitespace. Is ther a better option than running the answers down below twice. There are spaces --------------------- this huge.
idList.replaceAll(item -> item.replaceAll("\\s{2,}", "").trim());
I got it :D
Change
item.replaceAll("\n", "");
to
idList.set(i,item.replaceAll("\n", ""));
item.replaceAll doesn't modify the state of the String referenced by item (which is impossible, since String is immutable). It returns a new String instead.
You can replace all your method to be like so :
public List<String> memberIDList() {
idList.replaceAll(item -> item.replaceAll("\n", ""));
return idList;
}
You can stream and map them:
idList.stream()
.map(str -> str.replaceAll("\n", ""))
.collect(Collectors.toList());
This will apply function str -> str.replaceAll("\n", "") to every element and collect them back to list. You can use this instead of your MemberIDList method.
P.S.: Method names are starting with lowercase in java.

Check starts-with for each element in array

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);
}
}

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);

Fastest way to put contents of Set<String> to a single String with words separated by a whitespace?

I have a few Set<String>s and want to transform each of these into a single String where each element of the original Set is separated by a whitespace " ".
A naive first approach is doing it like this
Set<String> set_1;
Set<String> set_2;
StringBuilder builder = new StringBuilder();
for (String str : set_1) {
builder.append(str).append(" ");
}
this.string_1 = builder.toString();
builder = new StringBuilder();
for (String str : set_2) {
builder.append(str).append(" ");
}
this.string_2 = builder.toString();
Can anyone think of a faster, prettier or more efficient way to do this?
With commons/lang you can do this using StringUtils.join:
String str_1 = StringUtils.join(set_1, " ");
You can't really beat that for brevity.
Update:
Re-reading this answer, I would prefer the other answer regarding Guava's Joiner now. In fact, these days I don't go near apache commons.
Another Update:
Java 8 introduced the method String.join()
String joined = String.join(",", set);
While this isn't as flexible as the Guava version, it's handy when you don't have the Guava library on your classpath.
If you are using Java 8, you can use the native
String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
method:
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
For example:
Set<String> strings = new LinkedHashSet<>();
strings.add("Java"); strings.add("is");
strings.add("very"); strings.add("cool");
String message = String.join("-", strings);
//message returned is: "Java-is-very-cool"
Set implements Iterable, so simply use:
String.join(" ", set_1);
As a counterpoint to Seanizer's commons-lang answer, if you're using Google's Guava Libraries (which I'd consider the 'successor' to commons-lang, in many ways), you'd use Joiner:
Joiner.on(" ").join(set_1);
with the advantage of a few helper methods to do things like:
Joiner.on(" ").skipNulls().join(set_1);
// If 2nd item was null, would produce "1, 3"
or
Joiner.on(" ").useForNull("<unknown>").join(set_1);
// If 2nd item was null, would produce "1, <unknown>, 3"
It also has support for appending direct to StringBuilders and Writers, and other such niceties.
Maybe a shorter solution:
public String test78 (Set<String> set) {
return set
.stream()
.collect(Collectors.joining(" "));
}
or
public String test77 (Set<String> set) {
return set
.stream()
.reduce("", (a,b)->(a + " " + b));
}
but native, definitely faster
public String test76 (Set<String> set) {
return String.join(" ", set);
}
I don't have the StringUtil library available (I have no choice over that) so using standard Java I came up with this ..
If you're confident that your set data won't include any commas or square brackets, you could use:
mySet.toString().replaceAll("\\[|\\]","").replaceAll(","," ");
A set of "a", "b", "c" converts via .toString() to string "[a,b,c]".
Then replace the extra punctuation as necesary.
Filth.
I use this method:
public static String join(Set<String> set, String sep) {
String result = null;
if(set != null) {
StringBuilder sb = new StringBuilder();
Iterator<String> it = set.iterator();
if(it.hasNext()) {
sb.append(it.next());
}
while(it.hasNext()) {
sb.append(sep).append(it.next());
}
result = sb.toString();
}
return result;
}
I'm confused about the code replication, why not factor it into a function that takes one set and returns one string?
Other than that, I'm not sure that there is much that you can do, except maybe giving the stringbuilder a hint about the expected capacity (if you can calculate it based on set size and reasonable expectation of string length).
There are library functions for this as well, but I doubt they're significantly more efficient.
This can be done by creating a stream out of the set and then combine the elements using a reduce operation as shown below (for more details about Java 8 streams check here):
Optional<String> joinedString = set1.stream().reduce(new
BinaryOperator<String>() {
#Override
public String apply(String t, String u) {
return t + " " + u;
}
});
return joinedString.orElse("");

Categories

Resources