Java Stream问题

时间:2016-10-27 19:01:09

标签: java function java-8 java-stream

我想在java 8中使用stream,for take(filter),skip和reverse但是我不知道如何...

这是我的代码:

Scanner scanner = new Scanner(System.in);
String[] array = scanner.nextLine().split(" ");
ArrayList<Integer> list = new ArrayList<Integer>();

for (int i = 0; i <array.length ; i++) {
    list.add(Integer.parseInt(array[i]));
}
Integer firstKElements = list.size()/4;
Integer middleKelemnts = list.size()/2;

现在,在我使用ArrayList填充integer后,我想为Array制作ArrayListfirstKElements,然后为middleKElements制作[8, 4, 3, 2]firstKElements {1}}(例如: [8] middleKElements[4, 3]<input type="text" class="form-control input-sm" id="cardNumber" data-encrypted-name="number" autocomplete="off" name="addCreditCardNumber"> p_neighbours = [] for x in [-1,0,1]: for y in [-1,0,1]: p_neighbours.append((P(0)+x,P(1)+y))

我怎么能用流来做?

2 个答案:

答案 0 :(得分:0)

您可以使用skip(long)limit(long)作为下一个:

List<Integer> list = Arrays.stream(scanner.nextLine().split(" "))
    .map(Integer::valueOf)
    .collect(Collectors.toList());

long firstKElements = list.size() / 4L;
long middleKelemnts = list.size() / 2L;

List<Integer> listFirstKElements = list.stream()
    .limit(firstKElements)
    .collect(Collectors.toList());
List<Integer> listMiddleKelemnts = list.stream()
    .skip(firstKElements)
    .limit(middleKelemnts)
    .collect(Collectors.toList());

但是出于这个目的List#subList(fromIndex, toIndex)似乎更合适使用Stream仅提取初始列表的子部分听起来像是Stream API的滥用行为。

答案 1 :(得分:0)

您使用限制并跳过如下:

    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter values:");
    String in = scanner.nextLine();
    String[] array = in.split(" ");
    System.out.println(array);
    ArrayList<Integer> list = new ArrayList<Integer>();

    for (int i = 0; i < array.length; i++) {

        list.add(Integer.parseInt(array[i]));
    }
    Integer firstKElements = list.size() / 4;
    Integer middleKelemnts = list.size() / 2;

    // limit first array to size = firstKElements
    List one = list.stream().limit(firstKElements)
            .collect(Collectors.toList());
    System.out.println(one);

    // limit middle array to size = middleKelements (ignore firstKElements)
    List two = list.stream().skip(firstKElements).limit(middleKelemnts)
    .collect(Collectors.toList());
    System.out.println(two);