相关文章推荐
深沉的生菜  ·  解决sun.net.www.protocol ...·  2 年前    · 
老实的红豆  ·  API函数ShellExecute与Shel ...·  2 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

There is Data Set<Long> input and Map<Long, List<String>> store.

And I wanna get List only 10 size.

Map<Long, List<String>> datas = {...{;
Set<Long> input = {....};
List<String> output = new ArrayList<>();
for(Long key : input) {
    if(output.size() >= 10) break;
    List<String> tmp = datas.get(key);
    for(String val : tmp) {
        if(output.size() >= 10) break;
        output.add(val);

I can't use java 9 doWhile in stream

A corresponding stream pipeline can be

List<String> output = input.stream()
    .flatMap(i -> datas.get(i).stream()).limit(10)
    .collect(Collectors.toList());

Test:

Map<Long, List<String>> datas = new HashMap<>();
datas.put(1l, Arrays.asList("a", "b", "c", "d", "e", "f", "g"));
datas.put(2l, Arrays.asList("z", "y", "x", "w", "v", "u", "t"));
Set<Long> input = new LinkedHashSet<>(Arrays.asList(1l, 2l, 3l, 4l, 5l));
System.out.println(input.stream()
        .flatMap(i -> datas.get(i).stream()).limit(10)
        .collect(Collectors.toList()));

And that prints [a, b, c, d, e, f, g, z, y, x]

@EdgarHan It doesn't. limit(10) will stop it. Test the code (or add .peek(System.out::println) before collect to see what keys were looked up. And this code would throw a nullpointerexception if all keys from input were looked up. – ernest_k Feb 26, 2021 at 1:44 @ernest_k it may or may not see "w", that’s an implementation detail. With Java 8 before update 222, as well as Java 9, the peek before limit will even see "v", "u", and "t". See this Q&A. With a parallel stream, even the exceptions due to calling stream() on null may occur. It’s not a good idea to rely on the laziness… – Holger Feb 26, 2021 at 9:07 Yes that’s only an issue of the example program; for the OP’s task, the approach is sufficient. – Holger Feb 26, 2021 at 9:49

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.