Looking to use some streams in a project and replace some of the logic currently implemented. Not sure if this type of case is a good use case for java stream api. Lets say we have a collection and we want to iterate through it and check values from two objects within the collection, and only if both of them are true will we return a populated optional.
return Arrays.stream(someMultiDimensionalArray).flatMap(objectArray ->
.filter(MyClass.class::isInstance)
.filter(v -> v.value().equals(true))
//need to do something here to do, && (if another value in the collection is true also)
.findFirst();
/
boolean one = false;
for(int i=0; i<objectArray.length; i++){
if(!one && objectArray[i].hidden==true)
one = true;
if(objectArray[i].hidden == true && one)
return objectArray[i];
}
So, what you want is, if there are more than 1 objecst in the array that is having hidden == true, you want the 2nd one? (From what your code means).
So it is simply something like stream.filter(o -> o.hidden).skip(1).findFirst()
as you mentioned in comment above:
If there are two objects which have a true field in the collection then the condition is met.
your if statements code snippet in loop can be merged as:
boolean one = false;
for(int i=0; i<objectArray.length; i++){
if(!one && objectArray[i].hidden) {
one = true;
return objectArray[i];
}
}
Indeed, It can be simplified as further:
for(int i=0; i<objectArray.length; i++){
if(objectArray[i].hidden) {
return objectArray[i];
}
}
Then using for-each loop like this:
for(??? it: objectArray){
if(it.hidden) {
return it;
}
}
AND then using stream-api like this:
return Arrays.stream(objectArray).filter(it->it.hidden).findFirst();
maybe you need cast instance & return a stream in flatMap in the first approach:
return Arrays.stream(someMultiDimensionalArray).flatMap(objectArray ->
Arrays.stream(objectArray).filter(it->it.hidden).findFirst()
.map(Stream::of).orElse(Stream.empty())
)
.filter(MyClass.class::isInstance)
.map(MyClass.class::cast)
.filter(MyClass::value)
.findFirst();
Related
I was trying to write some functional programming code (using lambdas and streams from Java 8) to test if a string has unique characters in it (if it does, return true, if it does not, return false). A common way to do this using vanilla Java is with a data structure like a set, i.e.:
public static boolean oldSchoolMethod(String str) {
Set<String> set = new HashSet<>();
for(int i=0; i<str.length(); i++) {
if(!set.add(str.charAt(i) + "")) return false;
}
return true;
}
The set returns true if the character/object can be added to the set (because it did not exist there previously). It returns false if it cannot (it exists in the set already, duplicated value, and cannot be added). This makes it easy to break out the loop and detect if you have a duplicate, without needing to iterate through all length N characters of the string.
I know in Java 8 streams you cannot break out a stream. Is there anyway way to capture the return value of an intermediate stream operation, like adding to the set's return value (true or false) and send that value to the next stage of the pipeline (another intermediate operation or terminal stream operation)? i.e.
Arrays.stream(myInputString.split(""))
.forEach( i -> {
set.add(i) // need to capture whether this returns "true" or "false" and use that value later in
// the pipeline or is this bad/not possible?
});
One of the other ways I thought of solving this problem, is to just use distinct() and collect the results into a new string and if it is the same length as the original string, than you know it is unique, else if there are different lengths, some characters got filtered out for not being distinct, thus you know it is not unique when comparing lengths. The only issue I see here is that you have to iterate through all length N chars of the string, where the "old school" method best-case scenario could be done in almost constant time O(1), since it is breaking out the loop and returning as soon as it finds 1 duplicated character:
public static boolean java8StreamMethod(String str) {
String result = Arrays.stream(str.split(""))
.distinct()
.collect(Collectors.joining());
return result.length() == str.length();
}
Your solutions are all performing unnecessary string operations.
E.g. instead of using a Set<String>, you can use a Set<Character>:
public static boolean betterOldSchoolMethod(String str) {
Set<Character> set = new HashSet<>();
for(int i=0; i<str.length(); i++) {
if(!set.add(str.charAt(i))) return false;
}
return true;
}
But even the boxing from char to Character is avoidable.
public static boolean evenBetterOldSchoolMethod(String str) {
BitSet set = new BitSet();
for(int i=0; i<str.length(); i++) {
if(set.get(str.charAt(i))) return false;
set.set(str.charAt(i));
}
return true;
}
Likewise, for the Stream variant, you can use str.chars() instead of Arrays.stream(str.split("")). Further, you can use count() instead of collecting all elements to a string via collect(Collectors.joining()), just to call length() on it.
Fixing both issues yields the solution:
public static boolean newMethod(String str) {
return str.chars().distinct().count() == str.length();
}
This is simple, but lacks short-circuiting. Further, the performance characteristics of distinct() are implementation-dependent. In OpenJDK, it uses an ordinary HashSet under the hood, rather than BitSet or such alike.
This code might work for you:
public class Test {
public static void main(String[] args) {
String myInputString = "hellowrd";
HashSet<String> set = new HashSet<>();
Optional<String> duplicateChar =Arrays.stream(myInputString.split("")).
filter(num-> !set.add(num)).findFirst();
if(duplicateChar.isPresent()){
System.out.println("Not unique");
}else{
System.out.println("Unique");
}
}
}
Here using findFirst() I am able to find the first duplicate element. So that we don't need to continue on iterating rest of the characters.
What about just mapping to a boolean?
Arrays.stream(myInputString.split(""))
.map(set::add)
.<...>
That would solve your concrete issue, I guess, but it's not a very nice solution because the closures in stream chains should not have side-effects (that is exactly the point of functional programming...).
Sometimes the classic for-loop is still the better choice for certain problems ;-)
How can I create a method that would check whether or not a linked list contains any number larger than a parameter?
Let's say we have the linked list
[ 8 7 1 3 ]. This would return true and
[ 10 12 3 2] would return false.
Would this work?
public boolean f(int k) {
for (int=0; int<linkedList.size(); i++) {
if (linkedList.get(i)>k)
return false;
}
else
return true;
}
Also, I need to mention, this method would not change the list in any way and it should still work if the list contains null elements.
Thanks!
With Java 8
public boolean f(int k) {
return !linkedList.stream().anyMatch(i-> i> k );
}
clarification: I assume that you want to return false from the method in the case that even a single element is higher then the given k. Hence I use anyMatch since we only need to look for one element that is higher. There is no need to loop over the whole list.
No this will not work how you have it currently. You need to loop through the whole list before returning. The only time you should return prematurely is if you find a reason to return false in this context. So move your return true outside of your loop and then you'd be fine.
Also, try to give meaning to your method and class definitions. Saying obj.f(12) doesn't really say much, whereas obj.noElementGreaterThan(12) says a lot more.
for example:
public boolean noElementGreaterThan( int k ) {
for( int i = 0; i < linkedList.size(); i++ )
{
if( linkedList.get(i) > k )
return false;
}
return true;
}
The reason this works is because it will loop through the entire list of objects, comparing each to the value passed in (k). If the value is greater than k, then it will return false, meaning in this case that it does have an element greater than k.
using streams you could do like this:
public boolean f(int k) {
List<Integer> filtered = linkedList.stream().filter(i -> i > k).collect(Collectors.toList());
return !filtered.isEmpty();
}
Right now I have my boolean setup like this:
public boolean deleteItem(String p) {
for(int i = this.myList.size() - 1; i > -1; i--) {
if(this.myList.get(i) == p) {
this.myList.remove(i);
return true;
} else {
return false;
}
}
}
I'm trying to go through an arraylist and delete string p from the array list.However if string p does exist within the arraylist I need to delete the string and return true. If it does not exist I simply must return false. I'm coding in eclipse right now and it says that the return statements I have right now do not count as the "required" return statement that I need. How can I fix my code so that it has the return statement(s) in the right place?
Why reinvent the wheel?
public boolean deleteItem(String p) {
return this.list.remove(p);
}
You have a pathway through your code that does not return anything. If your list is empty then the loop will not execute and it will fall through to nothing. Also your loop will return as soon as you process your first item with either true or false.
The comment by John is correct.
"Remove the else block and move return false; outside the for loop.
Your function has a number of flaws.
You are doing a reference equality check and not the value equality check. For doing a value equality check, always use the "equals" method. You won't get any compiler errors for this kind of flaws. You will get undesired output.
Not all the control flows in your function has a return statement even though your method signature suggests a non-void return statement. This will produce a compiler error, the one that you are seeing in your code.
You are having multiple return statements. This is neither a compiler error nor a runtime error. However from good programming practice perspective, it's not the best idea to have multiple return statements. You can do a flag based return statement at the very end.
You are removing elements from a collection object while iterating through it. Depending on the type of the collection object you are using, it may throw a ConcurrentModificationException exception at run time. You need to use a fail-safe iterator instead if available.
I have tried to correct your program. See if this makes better sense:
public boolean deleteItem(String p) {
boolean itemFound = false;
//Assuming your myList object returns a fail safe iterator.
//If it returns a fail fast iterator instead, see the next option.
Iterator<String> iter = this.myList.iterator();
while(iter.hasNext()){
if(iter.next().equals(p)) {
iter.remove();
itemFound=true;
}
}
return itemFound;
}
The above program will work if the iterator is fail-safe. E.g. if your myList object is of type CopyOnWriteArrayList, its iterator will be fail safe. But if your myList object is of a type such a plain ArrayList, that returns a fail fast iterator, the above method will give you a CME.
If your myList collection object is of type List, you can try something as easy as:
public boolean deleteItem(String p) {
//removeAll will return true if at least 1 element is removed
return this.myList.removeAll(Collections.singletonList(p));
}
Alternately, if you are using Java 8, you can do something like following:
public boolean deleteItem(String p) {
//removeIf will return true if at least 1 element is removed
return this.myList.removeIf(item -> item != null && item.equals(p));
}
Hope this helps you a bit.
I want to check to see if two arrays share at least one term in common for my program.
I'm not quite sure what the code is to compare two arrays, but here is what I have so far;
if ((modWikiKeyArray).equals(inputArray[0]))
{
StringBuilder hyperlinkBuilder = new StringBuilder();
for(int i = 0; i < modWikiKeyArray.length; i++)
{
hyperlinkBuilder.append(modWikiKeyArray[i]);
}
}
How would I compare the array modWikiKeyArray to inputArray just to check and see if inputArray[0] is equal to any term inside of modWikiKeyArray?
Arrays.asList lets you build a list backed by an arbitrary array and use convenient Java Collections Framework features like the contains method:
Arrays.asList(oneArray).contains(elementFromAnotherArray)
If you want to see if the arrays have at least one element in common, you could build a HashSet out of one and loop over the other to try to find a common element:
boolean arraysIntersect(Object[] array1, Object[] array2) {
Set array1AsSet = HashSet(Arrays.asList(array1));
for (Object o : array2) {
if (array1AsSet.contains(o)) {
return true;
}
}
return false;
}
You can do the following
for(int i=0;i<modWikiKeyArray.length;i++) {
if(modWikiKeyArray[i].equals(inputArray[0])) {
System.out.println("Match found");
}
}
Note you need to override the equals() method of whatever array you are creating(Class of which array you are creating) .
Going by your code snippet, it looks like you need to check the presence of inputArray[0] only, in which case the following is sufficient:
boolean exists = java.util.Arrays.asList(modWikiKeyArray).contains(inputArray[0]);
Alternatively, you might also want to use ArrayUtils from Apache commons-lang:
boolean exists = ArrayUtils.contains(modWikiKeyArray, inputArray[0]);
However, if I read the text of your question, it seems you want to find if modWikiKeyArray contains at least one item from inputArray. For this you may also use retainAll from the Collections API to perform a list intersecion and see if the intersection list is non-empty.
However, the most primitive is still Aniket's method. However, I will modify it to reduce unnecessary operations:
int i = modWikiKeyArray.length - 1;
MyObject inputElement = inputArray[0];
boolean found = false;
for(; i != 0; i--) {
if(modWikiKeyArray[i].equals(inputElement)) {
found = true;
break;
}
}
I was looking through the code for an old Android application of mine, and I saw one thing I did to the effect of this:
boolean emptyArray = true;
for (int i = 0; i < array.size(); i++)
{
if (array.get(i) != null)
{
emptyArray = false;
break;
}
}
if (emptyArray == true)
{
return true;
}
return false;
There has to be a more efficient way of doing this -- but what is it?
emptyArray is defined as an ArrayList of Integers, which are inserted with a random number of null values (And later in the code, actual integer values).
Thanks!
Well, you could use a lot less code for starters:
public boolean isAllNulls(Iterable<?> array) {
for (Object element : array)
if (element != null) return false;
return true;
}
With this code, you can pass in a much wider variety of collections too.
Java 8 update:
public static boolean isAllNulls(Iterable<?> array) {
return StreamSupport.stream(array.spliterator(), true).allMatch(o -> o == null);
}
There is no more efficient way.
The only thing is you can do, is write it in more elegant way:
List<Something> l;
boolean nonNullElemExist= false;
for (Something s: l) {
if (s != null) {
nonNullElemExist = true;
break;
}
}
// use of nonNullElemExist;
Actually, it is possible that this is more efficient, since it uses Iterator and the Hotspot compiler has more info to optimize instead using size() and get().
It's not detection of contains only null values but it maybe be enough to use just contains(null) method on your list.
Simply Check it worked for me. Hope will work fine for you too!
if (arrayListSubQues!=null){
return true;}
else {
return false }
I use to do something like this :
// Simple loop to remove all 'null' from the list or a copy of the list
while array.remove(null) {
array.remove(null);
}
if (CollectionUtils.isEmpty(array)) {
// the list contained only nulls
}