Java Lambda Multiple Operations in a Single Thread

Scenario: I have an object with two functions →

<Integer> getA(); <Integer> getB();

I have a list of objects, for example List<MyObject> myObject.

Purpose Iterate over the list and get the sum of A and B in the list of objects.

My decision

myObject.stream().map(a -> a.getA()).collect(Collectors.summingDouble());

myObject.stream().map(a -> a.getB()).collect(Collectors.summingDouble());

Question: How can I do this at the same time? This way, I don't have to iterate over the original list twice.

@Edit: I did this because some of the filters that I used were O (n ^ 3). The view is really bad to do it twice.

Benchmark: it is really important if it is T or 2T, when the program runs for half an hour on i5. This was on much smaller data, and if I started the cluster, my data would also be large.

It doesn't matter if you can do it on one line!

+4
2

, :

public class Total {
    private int totalA = 0;
    private int totalB = 0;

    public void addA(int a) {
        totalA += a;
    }

    public void addB(int b) {
        totalB += b;
    }

    public int getTotalA() {
        return totalA;
    }

    public int getTotalB() {
        return totalB;
    }
}

,

Total total = objects.stream()
        .map(o -> (A) o)
        .collect(Total::new,
                (t, a) -> {
                    t.addA(a.getA());
                    t.addB(a.getB());
                },
                (t1, t2) -> { });
//check total.getTotalA() and total.getTotalB()

AbstractMap.SimpleEntry<Integer, Integer> Total, , , A/B .

+3

, , for. parallelism , , . .

int Integer.

List<String> list = Arrays.asList("tom","terry","john","kevin","steve");
int n = list.stream().collect(Collectors.summingInt(String::length));
int h = list.stream().collect(Collectors.summingInt(String::hashCode));

.

, :

  • ints . java.awt.Point int x int y.
  • ints . , .

:

List<String> list = Arrays.asList("tom","terry","john","kevin","steve");
long nh = list.stream()
    .collect(Collectors.summingLong((s) -> (s.hashCode() << 32) | s.length()));
    int n = (int) nh;
    int h = (int) (nh >> 32L);
0

Source: https://habr.com/ru/post/1651246/


All Articles