Совокупная сумма объектов типа значений в Java

Чтобы расширить некоторые комментарии к предыдущим ответам и дать более четкое сравнение, приведен пример обоих подходов, представленных до сих пор, с учетом того же ввода, фрагмента каналов для чтения и функции для вызова каждого значения, которое также необходимо чтобы узнать, к какому каналу пришло значение.

Существуют три основных различия между подходами:

  • Сложность. Хотя это может быть частично предпочтительным для читателя, я нахожу подход канала более идиоматичным, прямолинейным и удобочитаемым.
  • Производительность. В моей системе Xeon amd64 каналы goroutines + channels выполняют решение отражения примерно на два порядка (в общем отражение в Go часто медленнее и должно использоваться только тогда, когда это абсолютно необходимо). Конечно, если есть какая-либо значительная задержка либо в функции обработки результатов, либо при записи значений на входные каналы, это различие в производительности может стать незначительным.
  • Семантика блокировки / буферизации. Важность этого зависит от варианта использования. Чаще всего это либо не имеет значения, либо небольшая дополнительная буферизация в решении слияния goroutine может быть полезна для пропускной способности. Однако, если желательно иметь семантику, что только один писатель разблокирован, и это значение полностью обрабатывается до , любой другой писатель разблокирован, то это может быть достигнуто только с помощью решения отражения.

Обратите внимание, что оба подхода могут быть упрощены, если «id» передающего канала не требуется или если исходные каналы никогда не будут закрыты.

Канал объединения Goroutine:

// Process1 calls `fn` for each value received from any of the `chans`
// channels. The arguments to `fn` are the index of the channel the
// value came from and the string value. Process1 returns once all the
// channels are closed.
func Process1(chans []<-chan string, fn func(int, string)) {
    // Setup
    type item struct {
        int    // index of which channel this came from
        string // the actual string item
    }
    merged := make(chan item)
    var wg sync.WaitGroup
    wg.Add(len(chans))
    for i, c := range chans {
        go func(i int, c <-chan string) {
            // Reads and buffers a single item from `c` before
            // we even know if we can write to `merged`.
            //
            // Go doesn't provide a way to do something like:
            //     merged <- (<-c)
            // atomically, where we delay the read from `c`
            // until we can write to `merged`. The read from
            // `c` will always happen first (blocking as
            // required) and then we block on `merged` (with
            // either the above or the below syntax making
            // no difference).
            for s := range c {
                merged <- item{i, s}
            }
            // If/when this input channel is closed we just stop
            // writing to the merged channel and via the WaitGroup
            // let it be known there is one fewer channel active.
            wg.Done()
        }(i, c)
    }
    // One extra goroutine to watch for all the merging goroutines to
    // be finished and then close the merged channel.
    go func() {
        wg.Wait()
        close(merged)
    }()

    // "select-like" loop
    for i := range merged {
        // Process each value
        fn(i.int, i.string)
    }
}

Выбор выделения:

// Process2 is identical to Process1 except that it uses the reflect
// package to select and read from the input channels which guarantees
// there is only one value "in-flight" (i.e. when `fn` is called only
// a single send on a single channel will have succeeded, the rest will
// be blocked). It is approximately two orders of magnitude slower than
// Process1 (which is still insignificant if their is a significant
// delay between incoming values or if `fn` runs for a significant
// time).
func Process2(chans []<-chan string, fn func(int, string)) {
    // Setup
    cases := make([]reflect.SelectCase, len(chans))
    // `ids` maps the index within cases to the original `chans` index.
    ids := make([]int, len(chans))
    for i, c := range chans {
        cases[i] = reflect.SelectCase{
            Dir:  reflect.SelectRecv,
            Chan: reflect.ValueOf(c),
        }
        ids[i] = i
    }

    // Select loop
    for len(cases) > 0 {
        // A difference here from the merging goroutines is
        // that `v` is the only value "in-flight" that any of
        // the workers have sent. All other workers are blocked
        // trying to send the single value they have calculated
        // where-as the goroutine version reads/buffers a single
        // extra value from each worker.
        i, v, ok := reflect.Select(cases)
        if !ok {
            // Channel cases[i] has been closed, remove it
            // from our slice of cases and update our ids
            // mapping as well.
            cases = append(cases[:i], cases[i+1:]...)
            ids = append(ids[:i], ids[i+1:]...)
            continue
        }

        // Process each value
        fn(ids[i], v.String())
    }
}

[Полный код на игровой площадке Go .]

-3
задан Shubham Deshmukh 13 July 2018 в 06:47
поделиться

2 ответа

Спасибо за ответ. Первоначально я использовал

int getObjectVal = (int)obj[1])];

, но он выдавал ошибку

java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Integer

, но он работает, я пытался использовать код

int getObjectVal = ((BigInteger) obj[1]).intValue();
0
ответ дан Shubham Deshmukh 17 August 2018 в 13:31
поделиться

Если мы говорим о JSON, то из JSON вы можете использовать

arrayAbc=yourJSON.toJsonObject().getJsonArray("nameOfYourArrayField");

, и тогда у вас будет JSONarray значений. После этого вы можете использовать arrayAbc.stream().mapToInt(Integer::intValue).sum()

0
ответ дан azro 17 August 2018 в 13:31
поделиться
Другие вопросы по тегам:

Похожие вопросы: