标签: java-stream

如何转换 for 循环以找到 Java 流的第一次出现?

我有以下可以正常工作的代码

for (UniversityClass class : allClasses)
    {
        Period<Date> classDate = class.getClassDates();
        if (classDate.start().before(classEndDate)
                && classDate.end().after(classBeginDate))
        {
            classBooked = true;
            break;
        }
    }
Run Code Online (Sandbox Code Playgroud)

我试过这个:

allClasses.stream().filter(class -> {
            Period<Date> classDate = class.getClassDates();
            if (classDate.start().before(classEndDate)
                && classDate.end().after(classBeginDate))

            return true;
        }).findFirst().ifPresent($ -> {
            classBooked = true;
        });
Run Code Online (Sandbox Code Playgroud)

但这会引发添加 return 语句。此外,该classBooked变量需要声明为 final,但这是不可能的。正在做的错误是什么?

此外,一旦为真,我就需要break从它。这就是为什么我想到添加 findFirst().ifPresent()

java java-stream

14
推荐指数
3
解决办法
180
查看次数

如何懒惰地评估嵌套的 flatMap

我试图从两个潜在的无限流中召唤一个笛卡尔积,然后我通过limit().

到目前为止,这(大约)是我的策略:

@Test
void flatMapIsLazy() {
        Stream.of("a", "b", "c")
            .flatMap(s -> Stream.of("x", "y")
                .flatMap(sd -> IntStream.rangeClosed(0, Integer.MAX_VALUE)
                    .mapToObj(sd::repeat)))
            .map(s -> s + "u")
            .limit(20)
            .forEach(System.out::println);
}
Run Code Online (Sandbox Code Playgroud)

这不起作用。

显然,我的第二个流在第一次在管道上使用时就被当场进行了最终评估。它不会产生我可以按照自己的节奏使用的惰性流。

我认为.forEach这段代码中的原因ReferencePipeline#flatMap是:

@Override
public void accept(P_OUT u) {
    try (Stream<? extends R> result = mapper.apply(u)) {
        if (result != null) {
            if (!cancellationRequestedCalled) {
               result.sequential().forEach(downstream);
            }
            else {
                var s = result.sequential().spliterator();
                do { } while (!downstream.cancellationRequested() && s.tryAdvance(downstream));
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望上面的代码返回 20 …

java cartesian-product lazy-evaluation java-stream

14
推荐指数
1
解决办法
312
查看次数

将 List&lt;char[]&gt; 转换为数组 char[] 而不使用 System.arraycopy()

在 JavaList<char[]>中将a 转换/扁平化 的简单方法是什么?char[]

我知道我可以通过迭代List和 using来做到这一点System.arraycopy,但我想知道是否有更简单的方法来使用 Java 8 流来做到这一点?

也许是这样的,但不必将原语装箱char为Character:

List<char[]> listOfCharArrays = ...

Character[] charArray =
    Stream.of(listOfCharArrays )
        .flatMap(List::stream)
        .toArray(Character[]::new);
Run Code Online (Sandbox Code Playgroud)

java arrays char java-stream

14
推荐指数
4
解决办法
1465
查看次数

java 8嵌套流

假设你有这样的结构类:

public class Review{
    private Integer idReview;
    private String description;
    private ArrayList<RelReviewImage> images;
}

public class RelReviewImage{
    private Integer idRelReviewImage;
    private Integer idImage;
    private String name;
}
Run Code Online (Sandbox Code Playgroud)

使用Java 8和Streams,我们希望对对象进行过滤idImage并返回Review对象.
可能吗?一个级别很容易,但是我们找不到任何示例或文档的2个级别.

lambda java-8 java-stream

13
推荐指数
2
解决办法
2万
查看次数

如何以相反的顺序对IntStream进行排序

我正在使用.txt文件读取数字BufferedReader.我想颠倒这种蒸汽中元素的顺序,这样当它们被收集时,它们将从最高到最低排列.我不想在构建数组后进行排序,因为我不知道它中可能有多少个元素,我只需要最高的N个元素.

in = new BufferedReader(reader);
                int[] arr = in.lines()
                        .mapToInt(Integer::parseInt)
                        .sorted()
                        .limit((long) N)
                        .toArray();
Run Code Online (Sandbox Code Playgroud)

java java-8 java-stream

13
推荐指数
2
解决办法
7457
查看次数

在Stream reduce方法中,对于sum,标识总是0,对于乘法,1必须是1?

我继续学习java 8.

我发现了有趣的行为:

让我们看看代码示例:

// identity value and accumulator and combiner
        Integer summaryAge = Person.getPersons().stream()
                //.parallel()  //will return surprising result
                .reduce(1, (intermediateResult, p) -> intermediateResult + p.age,
                        (ir1, ir2) -> ir1 + ir2);
        System.out.println(summaryAge);
Run Code Online (Sandbox Code Playgroud)

和模型类:

public class Person {

    String name;

    Integer age;
    ///...

    public static Collection<Person> getPersons() {
        List<Person> persons = new ArrayList<>();
        persons.add(new Person("Vasya", 12));
        persons.add(new Person("Petya", 32));
        persons.add(new Person("Serj", 10));
        persons.add(new Person("Onotole", 18));
        return persons;
   }
}
Run Code Online (Sandbox Code Playgroud)

12 + 32 + 10 + 18 = 72
对于序列流,此代码始终返回73(72 …

java reduce java-8 java-stream

13
推荐指数
3
解决办法
6357
查看次数

在并行流上调用顺序会使所有先前的操作顺序进行

我有一个重要的数据集,并希望调用缓慢但干净的方法,而不是调用快速方法,副作用对第一个结果.我对中间结果不感兴趣,所以我不想收集它们.

显而易见的解决方案是创建并行流,进行慢速呼叫,再次使流顺序,并进行快速呼叫.问题是,所有代码都在单线程中执行,没有实际的并行性.

示例代码:

@Test
public void testParallelStream() throws ExecutionException, InterruptedException
{
    ForkJoinPool forkJoinPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors() * 2);
    Set<String> threads = forkJoinPool.submit(()-> new Random().ints(100).boxed()
            .parallel()
            .map(this::slowOperation)
            .sequential()
            .map(Function.identity())//some fast operation, but must be in single thread
            .collect(Collectors.toSet())
    ).get();
    System.out.println(threads);
    Assert.assertEquals(Runtime.getRuntime().availableProcessors() * 2, threads.size());
}

private String slowOperation(int value)
{
    try
    {
        Thread.sleep(100);
    }
    catch (InterruptedException e)
    {
        e.printStackTrace();
    }
    return Thread.currentThread().getName();
}
Run Code Online (Sandbox Code Playgroud)

如果我删除sequential,代码按预期执行,但显然,非并行操作将在多个线程中调用.

你能推荐一些关于这种行为的引用,或者某些方法可以避免临时收集吗?

java multithreading forkjoinpool java-stream

13
推荐指数
1
解决办法
2566
查看次数

使用Collectors.summingInt时如何获取自定义类型而不是Integer?

我目前正在创建一个Map<String, Map<LocalDate, Integer>>这样的Integer代表秒:

Map<String, Map<LocalDate, Integer>> map = stream.collect(Collectors.groupingBy(
            x -> x.getProject(),
            Collectors.groupingBy(
                x -> x.getDate(),
                Collectors.summingInt(t -> t.getDuration().toSecondOfDay())
            )
        ));
Run Code Online (Sandbox Code Playgroud)

我怎么能创建一个Map<String, Map<LocalDate, Duration>>?

java grouping java-8 java-stream collectors

13
推荐指数
1
解决办法
240
查看次数

使用流API将字符串全部设置为小写但首字母大写

我有一个List<String>只通过使用流API我将所有字符串设置为小写,将它们从最小的字符串排序到最大字符串并打印它们.我遇到的问题是将字符串的第一个字母大写.

这是我做的事.stream().map()吗?

public class Main {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("SOmE", "StriNgs", "fRom", "mE", "To", "yOU");
        list.stream()
            .map(n -> n.toLowerCase())
            .sorted((a, b) -> a.length() - b.length())
            .forEach(n -> System.out.println(n));;

    }

}
Run Code Online (Sandbox Code Playgroud)

输出:

me
to
you
some
from
strings
Run Code Online (Sandbox Code Playgroud)

期望的输出:

Me
To
You
Some
From
Strings
Run Code Online (Sandbox Code Playgroud)

java mapping capitalization java-8 java-stream

13
推荐指数
2
解决办法
664
查看次数

为什么LongSummaryStatistics实现IntConsumer?

为什么还有LongSummaryStatistics实现的IntConsumer时候IntSummaryStatistics实现IntConsumer?

java java-8 java-stream

13
推荐指数
1
解决办法
472
查看次数