io.vavr.collection.List类的使用及代码示例

x33g5p2x  于2022-01-24 转载在 其他  
字(10.5k)|赞(0)|评价(0)|浏览(395)

本文整理了Java中io.vavr.collection.List类的一些代码示例,展示了List类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。List类的具体详情如下:
包路径:io.vavr.collection.List
类名称:List

List介绍

[英]An immutable List is an eager sequence of elements. Its immutability makes it suitable for concurrent programming.

A List is composed of a head element and a tail List.

There are two implementations of the List interface:

  • Nil, which represents the empty List.
  • Cons, which represents a List containing one or more elements.
    A List is a Stack in the sense that it stores elements allowing a last-in-first-out (LIFO) retrieval.

Stack API:

  • #peek()
  • #peekOption()
  • #pop()
  • #popOption()
  • #pop2()
  • #pop2Option()
  • #push(Object)
  • #push(Object[])
  • #pushAll(Iterable)
    Methods to obtain a List:
// factory methods 
List.empty()                        // = List.of() = Nil.instance() 
List.of(x)                          // = new Cons<>(x, Nil.instance()) 
List.of(Object...)                  // e.g. List.of(1, 2, 3) 
List.ofAll(Iterable)                // e.g. List.ofAll(Stream.of(1, 2, 3)) = 1, 2, 3 
List.ofAll(<primitive array>) // e.g. List.of(new int[] {1, 2, 3}) = 1, 2, 3 
// int sequences 
List.range(0, 3)              // = 0, 1, 2 
List.rangeClosed(0, 3)        // = 0, 1, 2, 3

Note: A List is primarily a Seq and extends Stack for technical reasons (so Stack does not need to wrap List).

If operating on a List, please prefer

  • #prepend(Object) over #push(Object)
  • #prependAll(Iterable) over #pushAll(Iterable)
  • #tail() over #pop()
  • #tailOption() over #popOption()
    Factory method applications:
List<Integer>       s1 = List.of(1); 
List<Integer>       s2 = List.of(1, 2, 3); 
// = List.of(new Integer[] {1, 2, 3}); 
List<int[]>         s3 = List.ofAll(1, 2, 3); 
List<List<Integer>> s4 = List.ofAll(List.of(1, 2, 3)); 
List<Integer>       s5 = List.ofAll(1, 2, 3); 
List<Integer>       s6 = List.ofAll(List.of(1, 2, 3)); 
// cuckoo's egg 
List<Integer[]>     s7 = List.<Integer[]> of(new Integer[] {1, 2, 3});

Example: Converting a String to digits

// = List(1, 2, 3) 
List.of("123".toCharArray()).map(c -> Character.digit(c, 10))

See Okasaki, Chris: Purely Functional Data Structures (p. 7 ff.). Cambridge, 2003.
[中]不可变列表是一系列的元素。它的不变性使它适合于并发编程。
列表由头元素和尾元素组成。
列表接口有两种实现方式:
*Nil,表示空列表。
*Cons,表示包含一个或多个元素的列表。
列表是一个堆栈,它存储允许后进先出(LIFO)检索的元素。
堆栈API:
*#peek()
*#peek选项()
*#pop()
*#popOption()
*#pop2()
*#pop2Option()
*#推(物体)
*#推(对象[])
*#推球(可调)
获取列表的方法:

// factory methods 
List.empty()                        // = List.of() = Nil.instance() 
List.of(x)                          // = new Cons<>(x, Nil.instance()) 
List.of(Object...)                  // e.g. List.of(1, 2, 3) 
List.ofAll(Iterable)                // e.g. List.ofAll(Stream.of(1, 2, 3)) = 1, 2, 3 
List.ofAll(<primitive array>) // e.g. List.of(new int[] {1, 2, 3}) = 1, 2, 3 
// int sequences 
List.range(0, 3)              // = 0, 1, 2 
List.rangeClosed(0, 3)        // = 0, 1, 2, 3

注意:列表主要是一个Seq,出于技术原因扩展了堆栈(因此堆栈不需要包装列表)。
如果在列表上操作,请选择
*#在#推#上预旋(对象)
*#prependAll(Iterable)over#pushAll(Iterable)
*#tail()在#pop()上
*#tailOption()在#popooption()上
工厂方法应用:

List<Integer>       s1 = List.of(1); 
List<Integer>       s2 = List.of(1, 2, 3); 
// = List.of(new Integer[] {1, 2, 3}); 
List<int[]>         s3 = List.ofAll(1, 2, 3); 
List<List<Integer>> s4 = List.ofAll(List.of(1, 2, 3)); 
List<Integer>       s5 = List.ofAll(1, 2, 3); 
List<Integer>       s6 = List.ofAll(List.of(1, 2, 3)); 
// cuckoo's egg 
List<Integer[]>     s7 = List.<Integer[]> of(new Integer[] {1, 2, 3});

示例:将字符串转换为数字

// = List(1, 2, 3) 
List.of("123".toCharArray()).map(c -> Character.digit(c, 10))

参见Okasaki,Chris:纯功能数据结构(第7页及其后)。剑桥,2003年。

代码示例

代码示例来源:origin: vavr-io/vavr

static <T> List<List<T>> apply(List<T> elements, int k) {
    if (k == 0) {
      return List.of(List.empty());
    } else {
      return elements.zipWithIndex().flatMap(
          t -> apply(elements.drop(t._2 + 1), (k - 1)).map(c -> c.prepend(t._1))
      );
    }
  }
}

代码示例来源:origin: vavr-io/vavr

@SuppressWarnings("unchecked")
  private static <T> LinearSeq<T> toLinearSeq(Iterable<? extends T> iterable) {
    return (iterable instanceof LinearSeq) ? (LinearSeq<T>) iterable : List.ofAll(iterable);
  }
}

代码示例来源:origin: Swagger2Markup/swagger2markup

public Parameters(StringColumn... columns) {
    this.dataFrame = DataFrame.ofAll(List.of(columns).filter(TableComponent::isNotBlank));
  }
}

代码示例来源:origin: vavr-io/vavr

@Override
default List<T> takeRight(int n) {
  if (n <= 0) {
    return empty();
  }
  if (n >= length()) {
    return this;
  }
  return reverse().take(n).reverse();
}

代码示例来源:origin: vavr-io/vavr

@Override
default List<T> reverse() {
  return (length() <= 1) ? this : foldLeft(empty(), List::prepend);
}

代码示例来源:origin: vavr-io/vavr

@Override
default List<T> prependAll(Iterable<? extends T> elements) {
  Objects.requireNonNull(elements, "elements is null");
  return isEmpty() ? ofAll(elements) : ofAll(elements).reverse().foldLeft(this, List::prepend);
}

代码示例来源:origin: resilience4j/resilience4j

@RequestMapping(value = "events/{circuitBreakerName}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public CircuitBreakerEventsEndpointResponse getEventsFilteredByCircuitBreakerName(@PathVariable("circuitBreakerName") String circuitBreakerName) {
  return new CircuitBreakerEventsEndpointResponse(eventConsumerRegistry.getEventConsumer(circuitBreakerName).getBufferedEvents()
      .filter(event -> event.getCircuitBreakerName().equals(circuitBreakerName))
      .map(CircuitBreakerEventDTOFactory::createCircuitBreakerEventDTO).toJavaList());
}

代码示例来源:origin: vavr-io/vavr

/**
 * Alias for {@link List#of(Object)}
 *
 * @param <T>     Component type of element.
 * @param element An element.
 * @return A new {@link List} instance containing the given element
 */
public static <T> Seq<T> Seq(T element) {
  return List.of(element);
}

代码示例来源:origin: resilience4j/resilience4j

List<RetryEventDTO> eventsList = eventConsumerRegistry.getEventConsumer(retryName)
      .getBufferedEvents()
      .sorted(Comparator.comparing(RetryEvent::getCreationTime))
      .map(RetryEventDTO::createRetryEventDTO).toJavaList();
  d.success(new RetryEventsEndpointResponse(eventsList));
}).then(r -> ctx.render(Jackson.json(r)));
  List<RetryEventDTO> eventsList = eventConsumerRegistry.getEventConsumer(retryName)
      .getBufferedEvents()
      .sorted(Comparator.comparing(RetryEvent::getCreationTime))
      .filter(event -> event.getEventType() == RetryEvent.Type.valueOf(eventType.toUpperCase()))
      .map(RetryEventDTO::createRetryEventDTO).toJavaList();
  d.success(new RetryEventsEndpointResponse(eventsList));
}).then(r -> ctx.render(Jackson.json(r)));

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldPassPositiveDuration() {
  // Given
  final List<Long> positiveIntervals = List.of(10L, 99L, 981L);
  final List<Duration> positiveDurations = positiveIntervals.map(Duration::ofMillis);
  // When
  positiveDurations.forEach(IntervalFunction::of);
  positiveIntervals.forEach(IntervalFunction::of);
  positiveDurations.forEach(IntervalFunction::ofRandomized);
  positiveIntervals.forEach(IntervalFunction::ofRandomized);
  positiveDurations.forEach(IntervalFunction::ofExponentialBackoff);
  positiveIntervals.forEach(IntervalFunction::ofExponentialBackoff);
  positiveDurations.forEach(IntervalFunction::ofExponentialRandomBackoff);
  positiveIntervals.forEach(IntervalFunction::ofExponentialRandomBackoff);
  // Then should pass
}

代码示例来源:origin: vavr-io/vavr

/**
* Yields a result for elements of the cross product of the underlying List.
*
* @param f a function that maps an element of the cross product to a result
* @param <R> type of the resulting {@code List} elements
* @return an {@code List} of mapped results
*/
public <R> List<R> yield(Function<? super T1, ? extends R> f) {
  Objects.requireNonNull(f, "f is null");
  return ts1.map(f);
}

代码示例来源:origin: vavr-io/vavr

@SuppressWarnings("unchecked")
static <T, U, R> Tree<R> zip(Node<T> node, java.util.Iterator<? extends U> that, BiFunction<? super T, ? super U, ? extends R> mapper) {
  if (!that.hasNext()) {
    return Empty.instance();
  } else {
    final R value = mapper.apply(node.getValue(), that.next());
    final io.vavr.collection.List<Node<R>> children = (io.vavr.collection.List<Node<R>>) (Object) node
        .getChildren()
        .map(child -> zip(child, that, mapper))
        .filter(Tree::nonEmpty);
    return new Node<>(value, children);
  }
}

代码示例来源:origin: com.pragmaticobjects.oo.atom/atom-basis

@Override
  public final ClassFileLocatorSource classFileLocatorSource() {
    return new CflsExplicit(
      parts
        .map(ClassFileLocatorSource::classFileLocator)
        .transform(cflsl -> new ClassFileLocator.Compound(cflsl.toJavaList()))
    );
  }
}

代码示例来源:origin: vavr-io/vavr

@SuppressWarnings("unchecked")
static <T, U> Tree<U> flatMap(Node<T> node, Function<? super T, ? extends Iterable<? extends U>> mapper) {
  final Tree<U> mapped = ofAll(mapper.apply(node.getValue()));
  if (mapped.isEmpty()) {
    return empty();
  } else {
    final io.vavr.collection.List<Node<U>> children = (io.vavr.collection.List<Node<U>>) (Object) node
        .getChildren()
        .map(child -> flatMap(child, mapper))
        .filter(Tree::nonEmpty);
    return of(mapped.get(), children.prependAll(mapped.getChildren()));
  }
}

代码示例来源:origin: vavr-io/vavr

@Override
default List<T> dropRight(int n) {
  if (n <= 0) {
    return this;
  }
  if (n >= length()) {
    return empty();
  }
  return ofAll(iterator().dropRight(n));
}

代码示例来源:origin: vavr-io/vavr

Objects.requireNonNull(futures, "futures is null");
Objects.requireNonNull(predicate, "predicate is null");
final List<Future<? extends T>> list = List.ofAll(futures);
if (list.isEmpty()) {
  return successful(executor, Option.none());
} else {
  return run(executor, complete -> {
    final AtomicBoolean completed = new AtomicBoolean(false);
    final AtomicInteger count = new AtomicInteger(list.length());
    list.forEach(future -> future.onComplete(result -> {
      synchronized (count) {

代码示例来源:origin: vavr-io/vavr

static <T> Stream<T> apply(io.vavr.collection.List<T> front, io.vavr.collection.List<T> rear, Stream<T> remaining) {
    if (remaining.isEmpty()) {
      return remaining;
    } else if (front.isEmpty()) {
      return apply(rear.reverse(), io.vavr.collection.List.empty(), remaining);
    } else {
      return Stream.cons(front.head(),
          () -> apply(front.tail(), rear.prepend(remaining.head()), remaining.tail()));
    }
  }
}

代码示例来源:origin: vavr-io/vavr

/**
 * Creates a Queue that contains the elements of the given {@link java.util.stream.Stream}.
 *
 * @param javaStream A {@link java.util.stream.Stream}
 * @param <T>        Component type of the Stream.
 * @return A Queue containing the given elements in the same order.
 */
public static <T> Queue<T> ofAll(java.util.stream.Stream<? extends T> javaStream) {
  Objects.requireNonNull(javaStream, "javaStream is null");
  return new Queue<>(io.vavr.collection.List.ofAll(javaStream), io.vavr.collection.List.empty());
}

代码示例来源:origin: vavr-io/vavr

private static String toLispString(Tree<?> tree) {
  final String value = String.valueOf(tree.getValue());
  if (tree.isLeaf()) {
    return value;
  } else {
    final String children = tree.getChildren().map(child -> toLispString(child)).mkString(" ");
    return "(" + value + " " + children + ")";
  }
}

代码示例来源:origin: com.pragmaticobjects.oo.atom/atom-basis

@Override
  public final StackManipulation stackManipulation() {
    return new StackManipulation.Compound(
      tokens.map(StackManipulationToken::stackManipulation).toJavaList()
    );
  }
}

相关文章