public static Bar replaceBarIfChanged(BarSeries barSeries, Bar newBar) {
        List<Bar> bars = barSeries.getBarData();
        if (bars == null || bars.isEmpty())
            return null;
        for (int i = 0; i < bars.size(); i++) {
            Bar bar = bars.get(i);
            boolean isSameBar = bar.getBeginTime().isEqual(newBar.getBeginTime())
                    && bar.getEndTime().isEqual(newBar.getEndTime())
                    && bar.getTimePeriod().equals(newBar.getTimePeriod());
            if (isSameBar && !bar.equals(newBar))
                return bars.set(i, newBar);
        }
        return null;
    }
@Test
    public void replaceBarIfChangedTest() {

        final List<Bar> bars = new ArrayList<>();
        time = ZonedDateTime.of(2019, 6, 1, 1, 1, 0, 0, ZoneId.systemDefault());

        final Bar bar0 = new MockBar(time, 1d, 2d, 3d, 4d, 5d, 0d, 7, numFunction);
        final Bar bar1 = new MockBar(time.plusDays(1), 1d, 1d, 1d, 1d, 1d, 1d, 1, numFunction);
        final Bar bar2 = new MockBar(time.plusDays(2), 2d, 2d, 2d, 2d, 2d, 2d, 2, numFunction);
        final Bar bar3 = new MockBar(time.plusDays(3), 3d, 3d, 3d, 3d, 3d, 3d, 3, numFunction);
        final Bar bar4 = new MockBar(time.plusDays(4), 3d, 4d, 4d, 5d, 6d, 4d, 4, numFunction);
        final Bar bar5 = new MockBar(time.plusDays(5), 5d, 5d, 5d, 5d, 5d, 5d, 5, numFunction);
        final Bar bar6 = new MockBar(time.plusDays(6), 6d, 6d, 6d, 6d, 6d, 6d, 6, numFunction);

        bars.add(bar0);
        bars.add(bar1);
        bars.add(bar2);
        bars.add(bar3);
        bars.add(bar4);
        bars.add(bar5);
        bars.add(bar6);

        series = new BaseBarSeriesBuilder().withNumTypeOf(numFunction).withName("Series Name").withBars(bars).build();

        final Bar newBar3 = new MockBar(bar3.getEndTime(), 1d, 1d, 1d, 1d, 1d, 1d, 33, numFunction);
        final Bar newBar5 = new MockBar(bar5.getEndTime(), 1d, 1d, 1d, 1d, 1d, 1d, 55, numFunction);

        // newBar3 must be replaced with bar3
        Bar replacedBar3 = BarSeriesUtils.replaceBarIfChanged(series, newBar3);
        // newBar5 must be replaced with bar5
        Bar replacedBar5 = BarSeriesUtils.replaceBarIfChanged(series, newBar5);

        // the replaced bar must be the same as the previous bar
        assertEquals(bar3, replacedBar3);
        assertEquals(bar5, replacedBar5);
        assertNotEquals(bar2, replacedBar3);
        assertNotEquals(bar6, replacedBar5);

        // the replaced bar must removed from the series
        assertNotEquals(series.getBar(3), replacedBar3);
        assertNotEquals(series.getBar(5), replacedBar5);

        // the new bar must be stored in the series
        assertEquals(series.getBar(3), newBar3);
        assertEquals(series.getBar(5), newBar5);

        // no bar was added
        assertEquals(7, series.getBarData().size());
        assertEquals(7, series.getBarCount());
    }