Reputation: 1571
I have the following 3 files,
A.java:
class A {
private float b;
public A(float b) {
this.b = b;
}
public float getB() {
return b;
}
public String toString() {
return "A(b = " + b + ")";
}
}
C.java:
import java.util.Arrays;
class C {
private A[] d;
private int i = 0;
public C() {
d = new A[5];
}
public void addB(A b) {
d[i++] = b;
}
public String toString() {
return "C(b = " + Arrays.toString(d) + ")";
}
public void duplicate() {
A temp[] = Arrays.copyOf(d, d.length);
for (int cur = 0; cur < d.length; cur++) {
if (d[cur] == null) continue;
float currB = d[cur].getB();
for (int nxt = cur + 1; nxt < d.length; nxt++) {
if(d[nxt] == null) continue;
if(currB == d[nxt].getB()) {
temp[i++] = new A(currB * 0.5f);
}
}
}
d = temp;
}
}
D.java:
class D {
public static void main(String[] args) {
C c = new C();
c.addB(new A(3));
c.addB(new A(5));
c.addB(new A(3));
System.out.println(c.toString()); // C(b = [A(b = 3.0), A(b = 5.0), A(b = 3.0), null, null])
c.duplicate();
System.out.println(c.toString()); // C(b = [A(b = 3.0), A(b = 5.0), A(b = 3.0), A(b = 1.5), null])
}
}
This does what I expected it to do, which is add another item to the array with half the b
if two of the elements have the same returned float from A.getB()
. However, I was trying to implement this using the fancy Java 8 stream methods and lambda functions, like so:
Arrays.stream(d).anyMatch(cur -> {
if (cur == null) return false;
Arrays.stream(d).anyMatch(nxt -> {
if (nxt == null) return false;
System.out.println("Checking " + cur.getB() + " with " + nxt.getB());
return false;
});
return false;
});
And this outputted:
Checking 3.0 with 3.0
Checking 3.0 with 5.0
Checking 3.0 with 3.0
Checking 5.0 with 3.0
Checking 5.0 with 5.0
Checking 5.0 with 3.0
Checking 3.0 with 3.0
Checking 3.0 with 5.0
Checking 3.0 with 3.0
As you can see this follows the O(n²) algorithm which is not what I'm going for. In my original code I was "skipping" elements that I already checked by using the indexes from the outer nested for loop. So my question is, if there is a way to somehow implement this in the nested <Stream>.anyMatch(...)
that I attempted. Or is there a cleaner way of doing this?
Upvotes: 3
Views: 64
Reputation: 56433
You can replicate the duplicate
method using the Stream API as follows:
Stream<A> result =
IntStream.range(0, d.length)
.filter(cur -> d[cur] != null)
.flatMap(cur -> IntStream.range(cur + 1, d.length)
.filter(nxt -> d[nxt] != null)
.filter(nxt -> d[cur].getB() == d[nxt].getB())
.map(i -> cur))
.mapToObj(cur -> new A(d[cur].getB() * 0.5f));
d = Stream.concat(Arrays.stream(d), result)
.toArray(A[]::new);
Upvotes: 3