我想在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
制作ArrayList
或firstKElements
,然后为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))
)
我怎么能用流来做?
答案 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);