Lightweight-Stream-API


Source link: https://github.com/aNNiMON/Lightweight-Stream-API

Lightweight-Stream-API

Stream API from Java 8 rewritten on iterators for Java 7 and below.

Includes

  • Functional interfaces ( Supplier, Function, Consumer etc);
  • Stream/ IntStream/ LongStream/ DoubleStream (without parallel processing, but with a variety of additional methods and with custom operators);
  • Optional/ OptionalBoolean/ OptionalInt/ OptionalLong/ OptionalDouble classes;
  • Exceptional class - functional way to deal with exceptions;
  • Objects from Java 7.

Usage

Stream.of(/* array | list | set | map | anything based on Iterator/Iterable interface */)
  .filter(..)
  .map(..)
  ...
  .sorted()
  .forEach(..);
 Stream.of(value1, value2, value3)... IntStream.range(0, 10)...

Example project: https://github.com/aNNiMON/Android-Java-8-Stream-Example

Key features

Custom operators

Unlike Java 8 streams, Lightweight-Stream-API provides the ability to apply custom operators.

Stream.of(...)
  .custom(new Reverse<>())
  .forEach(...);
  public final class Reverse<T> implements UnaryOperator<Stream<T>> {

@Override
  public Stream<T> apply(Stream<T> stream) {

final Iterator<? extends T> iterator = stream.getIterator();

final ArrayDeque<T> deque = new ArrayDeque<T>();

while (iterator.hasNext()) {

 deque.addFirst(iterator.next());

}

return Stream.of(deque.iterator());

  
}
 
}

You can find more examples here.

Additional operators

In addition to backported Java 8 Stream operators, the library provides:

  • filterNot - negated filter operator

    // Java 8 stream.filter(((Predicate<String>) String::isEmpty).negate()) // LSA stream.filterNot(String::isEmpty)
  • select - filters instances of the given class

    // Java 8 stream.filter(Integer.class::isInstance) // LSA stream.select(Integer.class)
  • withoutNulls - filters only not null elements

    Stream.of("a", null, "c", "d", null)
      .withoutNulls() // [a, c, d]
  • sortBy - sorts by extractor function

    // Java 8 stream.sorted(Comparator.comparing(Person::getName)) // LSA stream.sortBy(Person::getName)
  • groupBy - groups by extractor function

    // Java 8 stream.collect(Collectors.groupingBy(Person::getName)).entrySet().stream() // LSA stream.groupBy(Person::getName)
  • chunkBy - partitions sorted stream by classifier function

    Stream.of("a", "b", "cd", "ef", "gh", "ij", "klmnn")
      .chunkBy(String::length) // [[a, b], [cd, ef, gh, ij], [klmnn]]
  • sample - emits every n-th elements

    Stream.rangeClosed(0, 10)
      .sample(2) // [0, 2, 4, 6, 8, 10]
  • slidingWindow - partitions stream into fixed-sized list and sliding over the elements

    Stream.rangeClosed(0, 10)
      .slidingWindow(4, 6) // [[0, 1, 2, 3], [6, 7, 8, 9]]
  • takeWhile / dropWhile - introduced in Java 9, limits/skips stream by predicate function

    Stream.of("a", "b", "cd", "ef", "g")
      .takeWhile(s -> s.length() == 1) // [a, b] Stream.of("a", "b", "cd", "ef", "g")
      .dropWhile(s -> s.length() == 1) // [cd, ef, g]
  • scan - iteratively applies accumulation function and returns Stream

    IntStream.range(1, 6)
      .scan((a, b) -> a + b) // [1, 3, 6, 10, 15]
  • indexed - adds an index to every element, result is IntPair

    Stream.of("a", "b", "c")
      .indexed() // [(0 : "a"), (1 : "b"), (2 : "c")]
  • filterIndexed / mapIndexed / takeWhileIndexed / takeUntilIndexed / dropWhileIndexed / reduceIndexed / forEachIndexed - indexed specialization of operators

    Stream.of("a", "b", "c")
      .mapIndexed((i, s) -> s + Integer.toString(i)) // [a0, b1, c2]

Throwable functions

No more ugly try/catch in lambda expressions.

// Java 8 stream.map(file -> {

  try {

return new FileInputStream(file);

  
}
 catch (IOException ioe) {

return null;
  
}
 
}
) // LSA stream.map(Function.Util.safe(FileInputStream::new))

Download

Download latest release or grab via Maven:

<dependency>
<groupId>com.annimon</groupId>
<artifactId>stream</artifactId>
<version>1.1.9</version> </dependency>

or Gradle:

dependencies {

...
compile 'com.annimon:stream:1.1.9'
... 
}

Also included version for Java ME. Checkout javame branch.

For use lambda expressions in Java 6, Java 7 or Android, take a look at Retrolambda repository.

Resources

Insanely easy way to define clickable links within a TextView.

This project shows how to visualize a tree structure using RecyclerView.

Library for securing your SharedPreferences information.

Android dex file extractor,anti-bangcle.

Sharedsqlite is a simple thread-safe database with a single table with a key-value schema where you can save your primitive data types that suites nowhere else excluding the headache of messing around with committing and reading from the SharedPreferences.

A sample of the new percent support library.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes