Is there underscore.js lib for java?

I often use javascript and find underscorejs very convenient for managing a data set, such as an array or an object.

I am very new to Java and wondering if there is a similar lib for Java?

+4
source share
2 answers

If you use Java 8, you can use the Java Stream class, which is a bit like Underscore, which is designed for functional programming. Here are some of the methods available , including map, cut, filter, min, max, etc.

For example, if the following code was underlined:

var words = ["Gallinule", "Escambio", "Aciform", "Entortilation", "Extensibility"];
var sum = _(words)
        .filter(function(w){return w[0] == "E"})
        .map(function(w){return w.length})
        .reduce(function(acc, curr){return acc + curr});
alert("Sum of letters in words starting with E... " + sum);

You can write it in Java 8 as follows:

String[] words = {"Gallinule", "Escambio", "Aciform", "Entortilation", "Extensibility"};
int sum = Arrays.stream(words)
        .filter(w -> w.startsWith("E"))
        .mapToInt(w -> w.length())
        .sum();
System.out.println("Sum of letters in words starting with E... " + sum);
+4

java 6/7. : underscore-java.

:

    String[] words = new String[] {"Gallinule", "Escambio", "Aciform", "Entortilation", "Extensibility"};
    int sum = (Integer) $.chain(words)
      .filter(new Predicate<String>() {
          public boolean test(String w) {
              return w.startsWith("E");
          }
      })
      .map(new Function<String, Integer>() {
          public Integer apply(String w) {
              return w.length();
          }
      })
      .reduce(new BiFunction<Integer, Integer, Integer>() {
          public Integer apply(Integer accum, Integer length) {
              return accum + length;
          }
      }, 0).item();
    System.out.println("Sum of letters in words starting with E... " + sum);

-lodash :

    int sum = (Integer) $.chain(words)
      .filter(new Predicate<String>() {
          public boolean test(String w) {
              return w.startsWith("E");
          }
      })
      .map(new Function<String, Integer>() {
          public Integer apply(String w) {
              return w.length();
          }
      })
      .sum().item();
    System.out.println("Sum of letters in words starting with E... " + sum);
+4

Source: https://habr.com/ru/post/1569938/


All Articles