• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Java Stream类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中java8.util.stream.Stream的典型用法代码示例。如果您正苦于以下问题:Java Stream类的具体用法?Java Stream怎么用?Java Stream使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Stream类属于java8.util.stream包,在下文中一共展示了Stream类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: expandSpecialCharactersInSingletonWord

import java8.util.stream.Stream; //导入依赖的package包/类
private Stream<String> expandSpecialCharactersInSingletonWord(String word) {

        if (word.length() == 1) {
            return stream(word.replace("@", "ARROBA")
                    .replace("´", "APOSTROFE")
                    .replace("%", "PORCIENTO")
                    .replace("#", "NUMERO")
                    .replace("!", "ADMIRACION")
                    .replace(".", "PUNTO")
                    .replace("$", "PESOS")
                    .replace("\"", "COMILLAS")
                    .replace("-", "GUION")
                    .replace("/", "DIAGONAL")
                    .replace("+", "SUMA")
                    .replace("(", "ABRE PARENTESIS")
                    .replace(")", "CIERRA PARENTESIS")
                    .split(" "));
        }
        return stream(word);
    }
 
开发者ID:josketres,项目名称:rfc-facil,代码行数:21,代码来源:JuristicPersonTenDigitsCodeCalculator.java


示例2: testUnBox

import java8.util.stream.Stream; //导入依赖的package包/类
public void testUnBox() {
        List<Double> list = java.util.Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0);
        Spliterator<Double> spliter = Spliterators.spliteratorUnknownSize(list.iterator(), 0);
        Stream<Double> stream = StreamSupport.stream(spliter, false);

//        double sum = Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0).stream().mapToDouble(i -> i).reduce(0.0, Double::sum);
        double sum = stream.mapToDouble(new ToDoubleFunction<Double>() {
            @Override
            public double applyAsDouble(Double i) {
                return i;
            }
        }).reduce(0.0, (DoubleBinaryOperator) new DoubleBinaryOperator() {
            @Override
            public double applyAsDouble(double v, double v2) {
                return v + v2;
            }
        });
        assertEquals(sum, 1.0 + 2.0 + 3.0 + 4.0 + 5.0);
    }
 
开发者ID:streamsupport,项目名称:streamsupport,代码行数:20,代码来源:DoublePrimitiveOpsTests.java


示例3: testEntrySetSizeRemove

import java8.util.stream.Stream; //导入依赖的package包/类
private void testEntrySetSizeRemove(String name, final Set<Map.Entry<Integer, Integer>> c) {
    Iterator<Map.Entry<Integer, Integer>> testIter = c.iterator();
    Map.Entry<Integer, Integer> first = testIter.next();
    assertTrue(c.remove(first));

    Supplier<Spliterator<Map.Entry<Integer, Integer>>> late = new Supplier<Spliterator<Map.Entry<Integer, Integer>>>() {
        @Override
        public Spliterator<Map.Entry<Integer, Integer>> get() {
            return Spliterators.spliterator(c, 0);
        }
    };

    Stream<Map.Entry<Integer, Integer>> stream = StreamSupport.stream(late, 0, false);

    Map.Entry<Integer, Integer> second = c.iterator().next();
    assertTrue(c.remove(second));
    Object[] result = stream.toArray();
    assertEquals(result.length, c.size());
}
 
开发者ID:streamsupport,项目名称:streamsupport,代码行数:20,代码来源:CollectionAndMapModifyStreamTest.java


示例4: testParSeq

import java8.util.stream.Stream; //导入依赖的package包/类
public void testParSeq() {
        List<Integer> list = Arrays.asList(1, 2, 3, 4);
        Spliterator<Integer> spliter = Spliterators.spliteratorUnknownSize(list.iterator(), 0);
        Stream<Integer> stream = StreamSupport.stream(spliter, false);

//        Stream<Integer> s = Arrays.asList(1, 2, 3, 4).stream().parallel();
        Stream<Integer> s = stream.parallel();
        assertTrue(s.isParallel());

        s = s.sequential();
        assertFalse(s.isParallel());

        s = s.sequential();
        assertFalse(s.isParallel());

        s = s.parallel();
        assertTrue(s.isParallel());

        s = s.parallel();
        assertTrue(s.isParallel());
    }
 
开发者ID:streamsupport,项目名称:streamsupport,代码行数:22,代码来源:StreamParSeqTest.java


示例5: addAddAll

import java8.util.stream.Stream; //导入依赖的package包/类
public void addAddAll() {
    final StringJoiner sj = new StringJoiner(DASH, "{", "}");
    sj.add(ONE);

    ArrayList<String> nextOne = new ArrayList<String>();
    nextOne.add(TWO);
    nextOne.add(THREE);
    Stream<String> stream = StreamSupport.stream(nextOne);
    stream.forEachOrdered(new java8.util.function.Consumer<String>() {
        @Override
        public void accept(String t) {
            sj.add(t);
        }
    });

    String expected = "{"+ONE+DASH+TWO+DASH+THREE+"}";
    assertEquals(sj.toString(), expected);
}
 
开发者ID:streamsupport,项目名称:streamsupport,代码行数:19,代码来源:StringJoinerTest.java


示例6: addAlladd

import java8.util.stream.Stream; //导入依赖的package包/类
void addAlladd() {
    final StringJoiner sj = new StringJoiner(DASH, "{", "}");

    ArrayList<String> firstOne = new ArrayList<String>();
    firstOne.add(ONE);
    firstOne.add(TWO);
    Stream<String> stream = StreamSupport.stream(firstOne);
    stream.forEachOrdered(new java8.util.function.Consumer<String>() {
        @Override
        public void accept(String t) {
            sj.add(t);
        }
    });

    sj.add(THREE);

    String expected = "{"+ONE+DASH+TWO+DASH+THREE+"}";
    assertEquals(sj.toString(), expected);
}
 
开发者ID:streamsupport,项目名称:streamsupport,代码行数:20,代码来源:StringJoinerTest.java


示例7: testDropWhileMulti

import java8.util.stream.Stream; //导入依赖的package包/类
private void testDropWhileMulti(Consumer<Stream<Integer>> mRef,
                                Consumer<IntStream> mInt,
                                Consumer<LongStream> mLong,
                                Consumer<DoubleStream> mDouble) {
    Map<String, Supplier<Stream<Integer>>> sources = new HashMap<>();
    sources.put("IntStream.range().boxed()",
                () -> IntStreams.range(0, DROP_SOURCE_SIZE).boxed());
    sources.put("IntStream.range().boxed().unordered()",
                () -> IntStreams.range(0, DROP_SOURCE_SIZE).boxed().unordered());
    sources.put("LinkedList.stream()",
                () -> StreamSupport.stream(IntStreams.range(0, DROP_SOURCE_SIZE).boxed()
                        .collect(toCollection(LinkedList::new))
                        ));
    sources.put("LinkedList.stream().unordered()",
                () -> StreamSupport.stream(IntStreams.range(0, DROP_SOURCE_SIZE).boxed()
                        .collect(toCollection(LinkedList::new))
                        )
                        .unordered());
    testWhileMulti(sources, mRef, mInt, mLong, mDouble);
}
 
开发者ID:streamsupport,项目名称:streamsupport,代码行数:21,代码来源:WhileOpStatefulTest.java


示例8: ConcatTest

import java8.util.stream.Stream; //导入依赖的package包/类
public ConcatTest(String scenario, Collection<Integer> c1, Collection<Integer> c2, Collection<Integer> expected) {
    this.scenario = scenario;
    this.c1 = c1;
    this.c2 = c2;
    this.expected = expected;


    // verify prerequisite
    Stream<Integer> s1s = StreamSupport.stream(c1, Characteristics.get(c1));
    Stream<Integer> s2s = StreamSupport.stream(c2, Characteristics.get(c2));
    Stream<Integer> s1p = StreamSupport.stream(c1, Characteristics.get(c1), true);
    Stream<Integer> s2p = StreamSupport.stream(c2, Characteristics.get(c2), true);
    assertTrue(s1p.isParallel());
    assertTrue(s2p.isParallel());
    assertFalse(s1s.isParallel());
    assertFalse(s2s.isParallel());

    assertTrue(s1s.spliterator().hasCharacteristics(Spliterator.ORDERED));
    assertTrue(s1p.spliterator().hasCharacteristics(Spliterator.ORDERED));
    assertTrue(s2s.spliterator().hasCharacteristics(Spliterator.ORDERED));
    assertTrue(s2p.spliterator().hasCharacteristics(Spliterator.ORDERED));
}
 
开发者ID:streamsupport,项目名称:streamsupport,代码行数:23,代码来源:ConcatTest.java


示例9: testOps

import java8.util.stream.Stream; //导入依赖的package包/类
@Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class)
public void testOps(String name, TestData.OfRef<Integer> data) {
    // @@@ More things to test here:
    //     - Every value in data is present in right bucket
    //     - Total number of values equals size of data

    for (MapperData<Integer, ?> md : getMapperData(data)) {
        Collector<Integer, ?, Map<Object, List<Integer>>> tab = Collectors.groupingBy(md.m);
        Map<Object, List<Integer>> result =
                withData(data)
                .terminal((Stream<Integer> s) -> s, s -> s.collect(tab))
                .resultAsserter((act, exp, ord, par) -> {
                    if (par & !ord) {
                        GroupByOpTest.assertMultiMapEquals(act, exp);
                    }
                    else {
                        GroupByOpTest.assertObjectEquals(act, exp);
                    }
                })
                .exercise();
        assertEquals(result.keySet().size(), md.expectedSize);
    }
}
 
开发者ID:streamsupport,项目名称:streamsupport,代码行数:24,代码来源:GroupByOpTest.java


示例10: testConsumed

import java8.util.stream.Stream; //导入依赖的package包/类
public void testConsumed() {
    Stream<Integer> s1 = StreamSupport.stream(countTo(100));
    try {
        s1.forEach(i -> {});
        // Adding onClose handler when stream is consumed is illegal
        // handler must not be registered
        checkISE(() -> s1.onClose(() -> fail("s1")));
    } finally {
        if (s1 != null) {
            s1.close();
        }
    }

    // close() must be idempotent:
    // second close() invoked at the end of try-with-resources must have no effect
    Stream<Integer> s2 = StreamSupport.stream(countTo(100));
    try {
        s2.close();
        // Adding onClose handler when stream is closed is also illegal
        checkISE(() -> s2.onClose(() -> fail("s2")));
    } finally {
        if (s2 != null) {
            s2.close();
        }
    }
}
 
开发者ID:streamsupport,项目名称:streamsupport,代码行数:27,代码来源:StreamCloseTest.java


示例11: assertValue

import java8.util.stream.Stream; //导入依赖的package包/类
@Override
void assertValue(M map, Supplier<Stream<T>> source, boolean ordered) throws Exception {
    if (!clazz.isAssignableFrom(map.getClass()))
        fail(String.format("Class mismatch in ToMapAssertion: %s, %s", clazz, map.getClass()));
    Set<K> uniqueKeys = source.get().map(keyFn).collect(toSet());
    assertEquals(uniqueKeys, map.keySet());
    source.get().forEach(t -> {
        K key = keyFn.apply(t);
        V v = source.get()
                    .filter(e -> key.equals(keyFn.apply(e)))
                    .map(valueFn)
                    .reduce(mergeFn)
                    .get();
        assertEquals(map.get(key), v);
    });
}
 
开发者ID:streamsupport,项目名称:streamsupport,代码行数:17,代码来源:CollectorsTest.java


示例12: exerciseMapCollection

import java8.util.stream.Stream; //导入依赖的package包/类
private<T, M extends Map>
void exerciseMapCollection(TestData<T, Stream<T>> data,
                           Collector<T, ?, ? extends M> collector,
                           CollectorAssertion<T, M> assertion)
        throws Exception {
    boolean ordered = !collector.characteristics().contains(Collector.Characteristics.UNORDERED);

    M m = withData(data)
            .terminal(s -> s.collect(collector))
            .resultAsserter(mapTabulationAsserter(ordered))
            .exercise();
    assertion.assertValue(m, () -> data.stream(), ordered);

    m = withData(data)
            .terminal(s -> s.unordered().collect(collector))
            .resultAsserter(mapTabulationAsserter(ordered))
            .exercise();
    assertion.assertValue(m, () -> data.stream(), false);
}
 
开发者ID:streamsupport,项目名称:streamsupport,代码行数:20,代码来源:CollectorsTest.java


示例13: testGroupingByWithFlatMapping

import java8.util.stream.Stream; //导入依赖的package包/类
@Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class)
public void testGroupingByWithFlatMapping(String name, TestData.OfRef<Integer> data) throws Exception {
    Function<Integer, Integer> classifier = i -> i % 3;
    Function<Integer, Stream<Integer>> flatMapperByNull = i -> null;
    Function<Integer, Stream<Integer>> flatMapperBy0 = i -> RefStreams.empty();
    Function<Integer, Stream<Integer>> flatMapperBy2 = i -> RefStreams.of(i, i);

    exerciseMapCollection(data,
                          groupingBy(classifier, flatMapping(flatMapperByNull, toList())),
                          new GroupingByAssertion<>(classifier, HashMap.class,
                                                    new FlatMappingAssertion<>(flatMapperBy0,
                                                                               new ToListAssertion<>())));
    exerciseMapCollection(data,
                          groupingBy(classifier, flatMapping(flatMapperBy0, toList())),
                          new GroupingByAssertion<>(classifier, HashMap.class,
                                                    new FlatMappingAssertion<>(flatMapperBy0,
                                                                               new ToListAssertion<>())));
    exerciseMapCollection(data,
                          groupingBy(classifier, flatMapping(flatMapperBy2, toList())),
                          new GroupingByAssertion<>(classifier, HashMap.class,
                                                    new FlatMappingAssertion<>(flatMapperBy2,
                                                                               new ToListAssertion<>())));
}
 
开发者ID:streamsupport,项目名称:streamsupport,代码行数:24,代码来源:CollectorsTest.java


示例14: testWhileMulti

import java8.util.stream.Stream; //导入依赖的package包/类
private void testWhileMulti(TestData.OfRef<Integer> data,
                            ResultAsserter<Iterable<Integer>> ra,
                            Function<Stream<Integer>, Stream<Integer>> mRef,
                            Function<IntStream, IntStream> mInt,
                            Function<LongStream, LongStream> mLong,
                            Function<DoubleStream, DoubleStream> mDouble) {
    Map<String, Function<Stream<Integer>, Stream<Integer>>> ms = new HashMap<>();
    ms.put("Ref", mRef);
    ms.put("Int", s -> mInt.apply(s.mapToInt(e -> e)).mapToObj(e -> e));
    ms.put("Long", s -> mLong.apply(s.mapToLong(e -> e)).mapToObj(e -> (int) e));
    ms.put("Double", s -> mDouble.apply(s.mapToDouble(e -> e)).mapToObj(e -> (int) e));
    ms.put("Ref using defaults", s -> mRef.apply(DefaultMethodStreams.delegateTo(s)));
    ms.put("Int using defaults", s -> mInt.apply(DefaultMethodStreams.delegateTo(s.mapToInt(e -> e))).mapToObj(e -> e));
    ms.put("Long using defaults", s -> mLong.apply(DefaultMethodStreams.delegateTo(s.mapToLong(e -> e))).mapToObj(e -> (int) e));
    ms.put("Double using defaults", s -> mDouble.apply(DefaultMethodStreams.delegateTo(s.mapToDouble(e -> e))).mapToObj(e -> (int) e));

    testWhileMulti(data, ra, ms);
}
 
开发者ID:streamsupport,项目名称:streamsupport,代码行数:19,代码来源:WhileOpTest.java


示例15: testParSeq

import java8.util.stream.Stream; //导入依赖的package包/类
public void testParSeq() {
    Stream<Integer> s = StreamSupport.stream(Arrays.asList(1, 2, 3, 4)).parallel();
    assertTrue(s.isParallel());

    s = s.sequential();
    assertFalse(s.isParallel());

    s = s.sequential();
    assertFalse(s.isParallel());

    s = s.parallel();
    assertTrue(s.isParallel());

    s = s.parallel();
    assertTrue(s.isParallel());
}
 
开发者ID:streamsupport,项目名称:streamsupport,代码行数:17,代码来源:StreamParSeqTest.java


示例16: testClose

import java8.util.stream.Stream; //导入依赖的package包/类
@Test
public void testClose() {
    AtomicInteger before = new AtomicInteger();
    AtomicInteger onClose = new AtomicInteger();

    Supplier<Stream<Integer>> s = () -> {
        before.set(0); onClose.set(0);
        return RefStreams.of(1, 2).peek(e -> before.getAndIncrement());
    };

    s.get().flatMap(i -> RefStreams.of(i, i).onClose(onClose::getAndIncrement)).count();
    assertEquals(before.get(), onClose.get());

    s.get().flatMapToInt(i -> IntStreams.of(i, i).onClose(onClose::getAndIncrement)).count();
    assertEquals(before.get(), onClose.get());

    s.get().flatMapToLong(i -> LongStreams.of(i, i).onClose(onClose::getAndIncrement)).count();
    assertEquals(before.get(), onClose.get());

    s.get().flatMapToDouble(i -> DoubleStreams.of(i, i).onClose(onClose::getAndIncrement)).count();
    assertEquals(before.get(), onClose.get());
}
 
开发者ID:streamsupport,项目名称:streamsupport,代码行数:23,代码来源:FlatMapOpTest.java


示例17: mapLessonsForWeek

import java8.util.stream.Stream; //导入依赖的package包/类
private Stream<IFlexible> mapLessonsForWeek(SchoolWeek schoolWeek) {
    Stream.Builder<IFlexible> builder = RefStreams.builder();

    Map<LocalDate, List<EnrichedLesson>> days = StreamSupport.stream(schoolWeek.lessons())
            .collect(Collectors.groupingBy(EnrichedLesson::date));
    for (LocalDate date = schoolWeek.weekStart(); date.isBefore(schoolWeek.weekStart().plusWeeks(1)); date = date.plusDays(1)) {
        LessonHeaderItem header = new LessonHeaderItem(date);
        List<EnrichedLesson> schoolDay = days.get(date);
        if (schoolDay == null || schoolDay.isEmpty()) {
            builder.add(new EmptyDayItem(header, date));
        } else {
            ImmutableMap<Integer, EnrichedLesson> lessonMap = Maps.uniqueIndex(schoolDay, BaseLesson::lessonNo);

            int maxLessonNumber = Collections.max(lessonMap.keySet());
            int minLessonNumber = Collections.min(lessonMap.keySet());

            minLessonNumber = Math.min(1, minLessonNumber);

            for (int l = minLessonNumber; l <= maxLessonNumber; l++) {
                EnrichedLesson lesson = lessonMap.get(l);
                if (lesson != null) {
                    builder.add(new LessonItem(header, lesson, getContext()));
                } else {
                    builder.add(new MissingLessonItem(header, l));
                }
            }
        }
    }
    return builder.build();
}
 
开发者ID:shymmq,项目名称:librus-client,代码行数:31,代码来源:TimetableFragment.java


示例18: findClosestItems

import java8.util.stream.Stream; //导入依赖的package包/类
public List<T> findClosestItems(LatLng center, int n, float initialRadius) {
    final int incFactor = 2;
    int found = 0;
    float currentDist = initialRadius;

    Stream<T> nodes = null;

    if (this.mItems.size() < n)
        nodes = StreamSupport.stream(mItems).map(x -> x.getClusterItem()); // return all nodes
    else {
        while (found < n) {
            LatLngBounds bounds = LocationUtilities.calculateBoundingBox(center, currentDist);
            List<T> f = search(bounds);
            currentDist *= incFactor;

            found = f.size();
            nodes = StreamSupport.stream(f);
        }
    }

    double mlat = center.latitude;
    double mlon = center.longitude;

    List<T> result = new ArrayList<>();
    nodes
            .sorted((x, y) ->
                    Double.compare(
                            distFrom(mlat, mlon, x.getPosition().latitude, x.getPosition().longitude),
                            distFrom(mlat, mlon, y.getPosition().latitude, y.getPosition().longitude)))
            .limit(n)
            .forEach(x -> result.add(x));

    return result;
}
 
开发者ID:JohannesRudolph,项目名称:Freifunk-App,代码行数:35,代码来源:SpatialDataSource.java


示例19: expandArabicNumerals

import java8.util.stream.Stream; //导入依赖的package包/类
private Stream<String> expandArabicNumerals(String word) {

        if (word.matches("[0-9]+")) {
            String number = normalize(SpanishNumbers.cardinal(Long.parseLong(word)));
            return stream(number.split(" "));
        } else {
            return stream(word);
        }
    }
 
开发者ID:josketres,项目名称:rfc-facil,代码行数:10,代码来源:JuristicPersonTenDigitsCodeCalculator.java


示例20: expandRomanNumerals

import java8.util.stream.Stream; //导入依赖的package包/类
private Stream<String> expandRomanNumerals(String word) {

        if (RomanNumerals.isRomanNumeral(word)) {
            String number = normalize(SpanishNumbers.cardinal(RomanNumerals.parseInt(word)));
            return stream(number.split(" "));
        } else {
            return stream(word);
        }
    }
 
开发者ID:josketres,项目名称:rfc-facil,代码行数:10,代码来源:JuristicPersonTenDigitsCodeCalculator.java



注:本文中的java8.util.stream.Stream类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java Criteria类代码示例发布时间:2022-05-22
下一篇:
Java DocumentDictionaryService类代码示例发布时间:2022-05-22
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap