Skip to content

Repository files navigation

Android Java 8 Stream API Example

Demo app of using Java 8 features with Retrolambda and Lightweight-Stream-API.

Features:

  • () -> lambda expression

    findViewById(R.id.go).setOnClickListener(v -> {
    finalintindex = mActionSpinner.getSelectedItemPosition();
    if (index != Spinner.INVALID_POSITION) {
    action(actions[index]);
    }
    });
  • Method::references

    intcmp = Objects.compare(word, other.word, String::compareToIgnoreCase);
  • Stream.API()

    returnStream.of(lines)
    .map(str -> str.split("\t"))
    .filter(arr -> arr.length == 2)
    .map(arr -> newWord(arr[0], arr[1]))
    .collect(Collectors.toList());
  • switch for "string"

    switch (action) {
    case"filter 1":
    // Filter one wordstream = stream.filter(p -> p.getWord().split(" ").length == 1);
    break;
    case"filter 2+":
    // Filter two and more wordsstream = stream.filter(p -> p.getWord().split(" ").length >= 2);
    break;
    // ...
    }
  • try(with-resources) {}

    finalList<String> lines = newArrayList<>();
    try (finalInputStreamis = context.getAssets().open("words.txt");
    finalInputStreamReaderisr = newInputStreamReader(is, "UTF-8");
    finalBufferedReaderreader = newBufferedReader(isr)) {
    Stringline;
    while ( (line = reader.readLine()) != null ) {
    lines.add(line);
    }
    }
  • Objects (from Java 7)

    @Overridepublicbooleanequals(Objecto) {
    // ...finalWordother = (Word) o;
    returnObjects.equals(translate, other.translate) &&
    Objects.equals(word, other.word);
    }
    @OverridepublicinthashCode() {
    returnObjects.hash(word, translate);
    }
  • try {Exceptional} catch (functional try/catch)

    returnExceptional.of(() -> {
    finalInputStreamis = context.getAssets().open("words.txt");
    // ... operations which throws Exception ...returnlines;
    }).ifException(e -> Log.e("Java 8 Example", "Utils.readWords", e))
    .getOrElse(newArrayList<>());

Links

Demo app: Java8StreamExample.apk

Blog (Russian): Java 8 в Android со Stream API и лямбдами

Retrolambda: https://github.com/orfjackal/retrolambda

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

Screenshots

screen_1screen_2

About

Demo app of using Java 8 features with Retrolambda and Lightweight-Stream-API

Topics

Resources

Stars

111 stars

Watchers

6 watching

Forks

Releases

Packages

Contributors

Languages