Что такое guava java

Библиотека гуавы на Java

Google Guava — это набор общих библиотек для Java с открытым исходным кодом (децентрализованная модель разработки программного обеспечения, которая поощряет открытое сотрудничество), в основном разработанная инженерами Google. Это помогает в уменьшении ошибок кодирования. Он предоставляет служебные методы для коллекций, кэширования, поддержки примитивов, параллелизма, общих аннотаций, обработки строк, ввода-вывода и проверок. Самым последним выпуском является Guava 25.0, выпущенный 2018-04-25.

Почему гуава?

Пример: Как мы знаем, примитивные типы Java являются основными типами: byte, short, int, long, float, double, char, boolean. Эти типы нельзя использовать как объекты или как параметры типов для универсальных типов, что означает, что многие утилиты общего назначения не могут быть применены к ним. Guava предоставляет ряд этих универсальных утилит, способы взаимодействия между массивами примитивов и API-интерфейсами коллекций, преобразование из типов в представления байтовых массивов и поддержку поведения без знака в определенных типах.

Что такое guava java. Смотреть фото Что такое guava java. Смотреть картинку Что такое guava java. Картинка про Что такое guava java. Фото Что такое guava java

Давайте кратко рассмотрим утилиты и классы, которые Guava предоставляет поверх существующих библиотечных классов.

После статического импорта методы Guava понятны и однозначны.

Чтобы суммировать интересные функции Guava, обратитесь к таблице ниже:
Что такое guava java. Смотреть фото Что такое guava java. Смотреть картинку Что такое guava java. Картинка про Что такое guava java. Фото Что такое guava java

Мы будем обсуждать более подробно об этих классах и утилитах в наших будущих статьях.

Источник

Русские Блоги

Предисловие:

Обзор

Длина Java HashCode ограничена 32 битами, и нет никакого разделения между хэш-алгоритмами и данными (классами или методами), на которые они действуют.
Следовательно, его сложно заменить другим алгоритмом хеширования. В то же время значения хэша, генерируемые встроенным в Java алгоритмом хеширования, очень низки, отчасти потому, что они полагаются на низшие реализации хэш-кода, включая многие классы реализации в JDK.

Ява Object.hashCode Работает очень быстро, но не корректноКоллизия хэша Предотвращение проблем, но также и отсутствие ожиданий в отношении хеш-значений. Эта функция делает его очень подходящим для приложений в хеш-таблицах, потому что дополнительные хеш-коллизии будут только
приводит к небольшой потере производительности, и в то же время очень плохая дисперсия может быть решена с помощью второго метода хеширования (почти все в Java
Таким образом реализуются разумные алгоритмы хеширования (хеш-функции)). Однако во многих хэш-приложениях, кроме простых хеш-таблиц,
Object.hashCode Но этого недостаточно, поэтому com.google.common.hash Пакет разработан.

Организация (состав)

Глядя на Java-документацию пакета, мы обнаружим много разных классов, но не совсем понятно, как они работают вместе.

Давайте сначала посмотрим на часть кода этой библиотеки:

HashFunction (Hash метод-метод генерации значения Hash)

[ HashFunction ] Является ссылочно прозрачным методом без сохранения состояния (без возвращаемого значения), который отображает любой блок данных в адрес фиксированной длины,
Постарайтесь убедиться, что один и тот же ввод должен давать одинаковый вывод, а разные вводы дают разные результаты.

Хашер (хеш-объект)

Один HashFunciton Может предоставить [ Hasher ], он позволяет быстро вычислить хеш-значение входных данных.
Hasher Может принимать любую форму данных, байтовые массивы (байтовые массивы), срезы байтовых массивов (фрагменты байтовых массивов), последовательности символов (последовательности символов определенных наборов символов) и т. Д.
или любой предоставленный Funnel Объект реализации.

Hasher Достигнуто PrimitiveSink Интерфейс дляОбъект, который принимает потоки собственных типов данных Определяет API свободного стиля.

Funnel

Один [ Funnel ] Описывает, как разложить определенный объект на собственные значения поля. Например, у нас есть такой объект:

наш Funnel Может выглядеть так

HashCode

однажды Hasher Получив все входные значения, он может вызвать [ hash() ] Метод получения [ HashCode ] Примеры.
HashCode Поддержка проверки равенства, например [ asInt() ], [ asLong() ], [ asBytes() ] Методы и т. Д., Кроме того,
[ writeBytesTo(array, offset, maxLength) ] Метод поддерживает хеш-значение перед maxLength Байты длины записываются в массив.

BloomFilter (фильтр)

В хэш-библиотеке Guava есть встроенная BloomFilter Для этого вам нужно всего лишь один Funnel Класс реализации можно разложить на примитивные типы.
Вы можете передать [ create(Funnel funnel, int
expectedInsertions, double falsePositiveProbability) ] Метод получения [ BloomFilter ] Объект,
Уровень ложного обнаружения по умолчанию составляет всего 3%. BloomFilter предоставлена ​​[ boolean mightContain(T) ] с участием [ void put(T) ] Метод,
Их функция очевидна.

Hashing

Hashing Предоставляет множество хеш-функций и HashCode Инструментальный метод для объектных операций.

Предоставленные хеш-функции (предоставленные хеш-функции)

Алгоритм операций HashCode

Название методаописание
[ HashCode combineOrdered(Iterable ) ]Комбинируйте HashCode упорядоченным образом.Если два набора HashCode объединены таким образом, HashCode будет одинаковым, тогда элементы в двух наборах HashCode могут быть в одном порядке.
[ HashCode combineUnordered(Iterable ) ]Объедините HashCode неупорядоченным образом.Если два набора HashCode объединяются этим методом, HashCode будет одинаковым, тогда элементы в двух наборах HashCode могут быть в одном порядке при определенном методе сортировки.
[ int consistentHash(HashCode, int buckets) ]Назначьте согласованный хэш с размером заданного сегмента, чтобы свести к минимуму необходимость повторного сопоставления по мере роста сегментов. ПодробнееСогласованный хеш Википедия。

постскриптум: Я публикую весь контент на Github, вы можете присоединиться к нам, вы также можете задавать вопросы и обсуждать вместе, вот адрес моего проекта Github:【guava-jch】

Было бы лучше, если бы вы могли щелкнуть звездочку

В паблике ниже есть красивые барышни
Что такое guava java. Смотреть фото Что такое guava java. Смотреть картинку Что такое guava java. Картинка про Что такое guava java. Фото Что такое guava java

Источник

Использование Google Guava Cache для локального кэширования

Много раз нам приходилось получать данные из базы данных или другого веб-сервиса или загружать их из файловой системы. В случаях, когда это связано с сетевым вызовом, будут присутствовать сетевые задержки, ограничения пропускной способности сети. Один из подходов к решению этой проблемы заключается в том, чтобы иметь кэш, локальный для приложения.

Если ваше приложение охватывает несколько узлов, то кэш будет локальным для каждого узла, вызывая несогласованность данных. Это несоответствие данных может быть заменено для лучшей пропускной способности и меньших задержек. Но иногда, если несогласованность данных имеет существенное значение, тогда можно уменьшить ttl (время жизни) для объекта кэша, тем самым уменьшая продолжительность, в течение которой может возникать несогласованность данных.

Среди множества подходов к реализации локального кэша один из тех, которые я использовал в среде с высокой нагрузкой, — это кеш Guava. Мы использовали кеш guava для обслуживания более 80 000 запросов в секунду. И 90-й процентиль задержек составлял

5 мс. Это помогло нам масштабироваться при ограниченных требованиях к пропускной способности сети.

Часть ответа, которая нам полезна, выглядит так:

Что такое guava java. Смотреть фото Что такое guava java. Смотреть картинку Что такое guava java. Картинка про Что такое guava java. Фото Что такое guava java

Давайте теперь посмотрим на классы моделей, которые нам понадобятся для представления деталей книги:

Источник

Guava

Guava is a set of core Java libraries from Google that includes new collection types (such as multimap and multiset), immutable collections, a graph library, and utilities for concurrency, I/O, hashing, caching, primitives, strings, and more! It is widely used on most Java projects within Google, and widely used by many other companies as well.

Guava comes in two flavors.

Adding Guava to your build

To add a dependency on Guava using Maven, use the following:

To add a dependency using Gradle:

Snapshots and Documentation

Learn about Guava

Links

IMPORTANT WARNINGS

APIs marked with the @Beta annotation at the class or method level are subject to change. They can be modified in any way, or even removed, at any time. If your code is a library itself (i.e. it is used on the CLASSPATH of users outside your own control), you should not use beta APIs, unless you repackage them. If your code is a library, we strongly recommend using the Guava Beta Checker to ensure that you do not use any @Beta APIs!

APIs without @Beta will remain binary-compatible for the indefinite future. (Previously, we sometimes removed such APIs after a deprecation period. The last release to remove non- @Beta APIs was Guava 21.0.) Even @Deprecated APIs will remain (again, unless they are @Beta ). We have no plans to start removing things again, but officially, we’re leaving our options open in case of surprises (like, say, a serious security problem).

Guava has one dependency that is needed at runtime: com.google.guava:failureaccess:1.0

Serialized forms of ALL objects are subject to change unless noted otherwise. Do not persist these and assume they can be read by a future version of the library.

Our classes are not designed to protect against a malicious caller. You should not use them for communication between trusted and untrusted code.

Источник

Introduction to Google Guava

last modified July 13, 2020

This tutorial is an introduction to the Guava library. We look at some interesting features of the Guava library.

Guava

is an open-source set of common libraries for Java, mainly developed by Google engineers. Google has many Java projects. Guava is a solution for many common problems encountered in those projects, including areas of collections, math, functional idioms, input & output, and strings.

Some of the Guava’s features were already included in the JDK; for instance the String.join() method was introduced into JDK 8.

Guava Maven dependency

In our examples, we use the following Maven dependency.

Guava initializing collections

Guava allows to initialize collections in one line. JDK 8 does not have support for collection literals.

In the example, we create a map and a list using Guava’s factory methods.

A new map is created with the ImmutableMap.of() method.

A new list of strings is created with the Lists.newArrayList() method.

This is the output of the example.

Guava MoreObjects.toStringHelper()

The MoreObjects.toStringHelper() helps to create toString() methods with a consistent format easily, and it gives us control over what fields we include.

This is a Car bean. It contains a toString() method which gives a string representation of the object.

Instead of concatenating strings we have a cleaner solution with the MoreObjects.toStringHelper() method.

We create three car objects and pass them to the System.out.println() method. The method invokes the objects’ toString() methods.

This is the output of the example.

Guava FluentIterable

FluentIterable provides a powerful yet simple API for manipulating Iterable instances in a fluent manner. It allows us to filter and transform collections in various ways.

In this example, we have a Car bean.

In the code example, we have a list of car objects. We transform the list by reducing it only to cars which are less expensive than 30000 units.

A list of Car objects is created. There are no collection literals in JDK. We use Lists.newArrayList() from Guava to initialize the list.

A Predicate is created. A predicate is a function that returns a boolean value. This predicate determines whether the car is less expensive than 30000.

This is the output of the example.

Guava predicate

In general meaning, a predicate is a statement about something that is either true or false.

In the first example, we use a predicate to exclude null values from a collection.

We go through the filtered list and print its elements.

This is the output of the example.

The second example filters a collection by a specific textual pattern. In programming, predicates are often used to filter data.

The code example creates a list of items and later filters the list by a specific pattern.

The Predicates.containsPattern() returns a predicate that looks for items containing character ‘o’. The predicate is passed to the Collections2.filter() method.

These three words meet the criteria.

Reading all lines with Guava

The Files.readLines() allows to read all lines from a file in one shot.

Что такое guava java. Смотреть фото Что такое guava java. Смотреть картинку Что такое guava java. Картинка про Что такое guava java. Фото Что такое guava javaFigure: NetBeans project structure

The figure shows how the project structure looks in NetBeans.

We have this textual file in the src/main/resources directory.

The example reads all lines from the balzac.txt file and prints them to the console.

The file name is located in the src/main/resource directory.

With the Files.readLines() method, we read all lines from the balzac.txt file. The lines are stored in the list of strings.

We go through the list and print its elements.

Creating a new file with Guava

The Files.touch() method is used to create a new file or to update the timestamp on an existing file. The method is similar to the Unix touch command.

The example creates a newfile.txt in the project’s root directory.

Writing to a file with Guava

The Files.write() method writes data to a file.

The example writes a string consisting of fruit names to the fruits.txt file. The file is created in the project root directory.

Joining strings with Guava

In the example, we join elements of a list with a comma character.

This is the output of the example.

Splitting strings with Guava

The Splitter extracts non-overlapping substrings from an input string by recognizing appearances of a separator sequence.

The example uses the Splitter to split a sentence into words.

We have a sentence consisting of seven words.

The separator is a single space character. The splitToList() method splits the input into a list of strings.

The second example splits the input into three substrings.

In addition, the words are trimmed.

This is the output.

Guava preconditions

Preconditions are simple static methods to be called at the start of our own methods to verify correct arguments and state. The methods throw IllegalArgumentException on failure.

The example uses two preconditions.

We read input from the user. We expect a list of words.

The words specified are split into a list and the list is passed to the OutputItems() method

In the OutputItems() method we check that the list is not null and empty. With the checkArgument() method we ensure the validity of an expression; e.g. that the list is not null.

Calculating factorial with Guava

Guava has also tools for doing math calculations. The BigIntegerMath.factorial() computes a factorial.

The example prints the factorial of number 100.

This is the output of the example.

Calculating binomial with Guava

The BigIntegerMath.binomial() returns the binomial coefficient of n and k.

The example prints the binomial of 4 and 2.

Guava CharMatcher

CharMatcher provides some basic text processing methods.

The example removes any non-letter characters from the input string. The retainFrom() method returns a string containing all matching characters of a character sequence, in order.

The two digits are removed.

In the second example, we count the number of characters in the input strings.

The example counts the number of ‘n’ and ‘i’ characters in the input string.

The countIn() method returns the number of matching characters found in the character sequence.

This is the output of the example.

The CharMatcher.whitespace() determines whether the character is a white space.

In the third example, we remove white space from the string.

The white space is removed from the input string.

This is the output of the example.

Guava Ranges

Range allows to create various ranges easily. A range, or interval, defines the boundaries around a contiguous span of values; for example, integers from 1 to 10 inclusive.

In the example, we create three integer intervals.

This is the output of the example.

In this article, we have worked with the Google Guava library.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *