简体   繁体   English

(Java)如何将列表中的选定元素存储到数组中

[英](Java) How to store selected elements from a list into array

I have a list of elements:我有一个元素列表:

private List<Track> selection;

And I want to implement a function public Track[] selection()我想实现一个 function public Track[] selection()

which returns an array of selected tracks.它返回一个选定轨道的数组。 How to implement this?如何实施?

I was going to implement this: Swings: storing the selected values from List into an array.我打算实现这个: Swings:将列表中的选定值存储到数组中。 method, however it applies only for known number of elements.方法,但是它仅适用于已知数量的元素。

EDIT: Sorry to ask such a newbie question, but I tried any possible ways previously and nothing worked.编辑:很抱歉问这样一个新手问题,但我之前尝试了任何可能的方法,但没有任何效果。 OOP is new for me, and where else to find answers for questions if not here? OOP 对我来说是新的,如果不在这里,还能在哪里找到问题的答案? ^_^ ^_^

Consider the following minimal example for copying a list of Strings into an array and printing it:考虑以下将字符串列表复制到数组中并打印它的最小示例:

import java.util.Arrays;
import java.util.List;

public class Main {

  public static void main (String[] args) {
    List<String> stringList = Arrays.asList("H", "e", "l", "l", "o");
    String[] stringArray = stringList.toArray(new String[0]);
    System.out.println(Arrays.toString(stringArray)); // [H, e, l, l, o]
  }
}

Assuming the selection is a global value假设selection是一个全局值

public Track[] selection()
{
    return selection.toArray(new Track[0]);
}

Else, you can pass the selection List as an argument to the method;否则,您可以将selection列表作为参数传递给方法;

public Track[] selection(List<Track> input)
{
    return input.toArray(new Track[0]);
}

and then接着

Track[] result = selection( selectionList ) // List selection
public Track[] selection() {
    return this.selection.stream().filter(predicate-here).toArray(Track[]::new);
}

Your predicate might be, for instance: elem -> elem.getName().equals("something")例如,您的谓词可能是: elem -> elem.getName().equals("something")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM