Java stream api тренажер

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Java Stream API Exercises

gavinklfong/stream-api-exercises

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Correcting an error in application.properties and adding spring-boot-…

Git stats

Files

Failed to load latest commit information.

README.MD

Java Stream API Exercises

This GitHub project was created to serve as a playground for practicing Java Stream API. There are 15 exercises which introduce the API usage including filtering, transformation, sorting and the output to various formats.

It is a Spring Boot project with a example data model, repositories and a set of pre-defined data. The system automatically loads data into H2 in-memory database when the Spring Boot app starts up. Therefore, you can fetch data from database by calling repositories and experiment the usage of Java Stream API.

This project depends on Lombok Library which is an awesome code auto generation tool, it greatly simplify the source code. Read this article if you would like to know more about the usage.

To configure your IDE for the support of Lombok, check out the official documentation for detail.

The example data model consists of Customer, Order and Product. Customers can place multiple orders and each order would contain a number of products.

Data Model

The exercises and the sample solutions can be found in test source space.gavinklfong.demo.streamapi.StreamApiTest

You may refer to this article for detail walk through about the exercises.

Источник

Java Stream — Exercises, Practice, Solutions

Java Streams Exercises [ 8 exercises with solution]

[An editor is available at the bottom of the page to write and execute the scripts. Go to the editor]

Processing Data with Java SE 8 Streams:

Stream is a sequence of elements from a source that supports aggregate operations. Let’s break it down:

  • Sequence of elements: A stream provides an interface to a sequenced set of values of a specific element type. However, streams don’t actually store elements; they are computed on demand.
  • Source: Streams consume from a data-providing source such as collections, arrays, or I/O resources.
  • Aggregate operations: Streams support SQL-like operations and common operations from functional programing languages, such as filter, map, reduce, find, match, sorted, and so on.

1. Write a Java program to calculate the average of a list of integers using streams.

2. Write a Java program to convert a list of strings to uppercase or lowercase using streams.

3. Write a Java program to calculate the sum of all even, odd numbers in a list using streams.

4. Write a Java program to remove all duplicate elements from a list using streams.

5. Write a Java program to count the number of strings in a list that start with a specific letter using streams.

6. Write a Java program to sort a list of strings in alphabetical order, ascending and descending using streams.

7. Write a Java program to find the maximum and minimum values in a list of integers using streams.

8. Write a Java program to find the second smallest and largest elements in a list of integers using streams.

Java Code Editor

More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

What is the difference between a static and a non-static initialization code block

The code block with the static modifier signifies a class initializer; without the static modifier the code block is an instance initializer.

Class initializers are executed in the order they are defined (top down, just like simple variable initializers) when the class is loaded (actually, when it’s resolved, but that’s a technicality).

Instance initializers are executed in the order defined when the class is instantiated, immediately before the constructor code is executed, immediately after the invocation of the super constructor.

If you remove static from int a, it becomes an instance variable, which you are not able to access from the static initializer block. This will fail to compile with the error «non-static variable a cannot be referenced from a static context».

If you also remove static from the initializer block, it then becomes an instance initializer and so int a is initialized at construction.

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Лямбды и стримы, только практика, теории не будет

Java-университет

Всем привет. По случаю конкурса я решил написать тут не статью, но небольшой урок. Он будет про лямбды и стримы (stream) в Java. Если вы уже знакомы и используете их, то мотайте сразу к концу статьи, там будет небольшая подборка задач с JavaRush на которых можно потренироваться. Нужна java 8 и выше, закалка от JR, будет мало подробностей и много непонятного, сильное желание разобраться. Начнем с того, что я не буду объяснять историю появлений лямбд и стримов, просто сам её не знаю. Знаю только то, что пришли они из функционального стиля программирования, в наш ООП’шный. За мой короткий опыт обучения, просто показывал, как и что, некоторым людям сложновато понять идею, поэтому просто запоминайте, как пишется, поймете потом.

Лямбды

Лямбды и стримы, только практика, теории не будет - 1

Если вы совсем не знаете что такое лямбды, то: Лямбда выглядит так:

 (a, b) -> a.compareTo(b) (переменные) -> действие

Этого пока достаточно. Почитать теорию можно тут: ссылка раз, ссылка два, но мне кажется практика гораздо веселее. Предлагаю вам решить такую задачку: Напишите калькулятор 1 методом. Метод должен принимать 2 цифровых значения и кое-что ещё. Код ваш будет выглядеть примерно так:

 class Lambda < public static void main (String[] args) < >public static double calculate() < return null; >> 
  • Складывать;
  • умножать;
  • делить;
  • вычитать;
  • вычислять корень;
  • возводить в степень;
  • возводить в степень сумму аргументов поделенную на первое число + 117;
  • и все любые другие операции, которые сможете придумать.
  • if-else ;
  • char как указатель операции;
  • switch-case ;
  • и все остальное что вам придет в голову.
  • Только лямбды, задание то на них.

Лямбды и стримы, только практика, теории не будет - 3

Теперь перейдем к стримам (java streams). Это не те стримы о которых ты, читатель возможно подумал. Нет это не inputStream и не OutputStream . Это другое, это интереснее. Стримы пришли на замену циклам, не полностью, но все же. Подаются они с девизом «не объясняй, как делать, объясняй что делать». Небольшой пример стрима:

 List myList = Arrays.asList("a1", "a2", "b1", "c2", "c1"); myList.stream() .filter(s -> s.startsWith("c")) .map(String::toUpperCase) .sorted() .forEach(System.out::println); 
 myList.stream() // получить поток .filter(s -> s.startsWith("c")) //отфильтровать значения, оставить те, что начинаются с «с» .map(String::toUpperCase) // преобразовать все значения, перевести в верхний регистр .sorted() // отсортировать по порядку (дефолтный порядо) .forEach(System.out::println); // вывести каждый элемент на экран 
 List toSort = new ArrayList<>(); for(String s : myList) < if(s.startsWith("c"))< toSort.add(s.toUpperCase()); >> Collections.sort(toSort); for(String s : toSort)
  • 2208 — можно решить 1 стримом и 1 return, т.е. тело метода будет начинаться с return и дальше будет 1 целый стрим. Требование StringBuilder опустим.
  • 1908 — так же можно решить 1 стримом и 1 return. Начиная с чтения файла. Запись в файл через стримы как сделать я не знаю (если это возможно), пока делаем ручками. Т.е. Открываем только 2 потока (консоль и запись в файл). Чтение файла производим через методы, которые вернут нам либо лист, либо сразу стрим (google и javadoc).
  • 1907 — по идее тоже можно решить в один стрим. На входе стрима имя файла, на выходе количество слов world.
  • 1016 — немного извращенным способом можно решить в 1 стрим и 1 return;
  • 1821 — очень легко и в 1 стрим и 1 return. Эти 2 задачи познакомят вас с ещё одним методом стримов и ещё одним коллектором.
  • 1925 — можно одним стримом получить строку со словами и потом записать её в файл (можно ли писать в файл из стрима я не знаю)

Источник

Читайте также:  Php передача пост параметров
Оцените статью