读取对象流,然后更新对象中的计数

我需要解析排序数字的列表,然后找出顺序中有多少个数字的计数。


List<Integer> sortedNum = Arrays.asList(1, 2, 3, 8, 10);

因此,在此列表中,我期望结果为.{1;3},{8;1},{10;1}


如果没有流,代码看起来像这样,


Map<Integer, Integer> countMap = new HashMap<>();

int i = 0;

while (true) {

  int num = sortedNum.get(i);

  int count = 0;

  while (i < sortedNum.size()) {


    count++;

    i++;


    if (i == sortedNum.size()) {

      break;

    }

    if ((sortedNum.get(i - 1) + 1) < sortedNum.get(i)) {

      break;

    }

  }

  countMap.put(num, count);

  if (i == sortedNum.size()) {

    countMap.forEach((a, b) -> System.out.println(a + " " + b));

    break;

  }

}

是否可以通过迭代 IntStream 将其转换为流操作?任何帮助将不胜感激。


幕布斯6054654
浏览 78回答 2
2回答

HUH函数

我不认为这是一项受益于流API的任务。不过,您可以简化代码:Map<Integer, Integer> countMap = new LinkedHashMap<>();Integer v = sortedNum.isEmpty()? null: sortedNum.get(0);int count = 0;for(Integer i: sortedNum) {&nbsp; &nbsp; if(v + count == i) count++;&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; countMap.put(v, count);&nbsp; &nbsp; &nbsp; &nbsp; v = i;&nbsp; &nbsp; &nbsp; &nbsp; count = 1;&nbsp; &nbsp; }}if(v != null) countMap.put(v, count);countMap.forEach((a, b) -> System.out.println(a + " " + b));1 38 110 1可以通过实现自定义来表达这样的操作,但是代码会更复杂,同时基本上与累加器函数中的循环体相同。但除此之外,它还需要一个合并函数,这对于此操作来说并非微不足道。Collector

呼唤远方

我假设你想要一个新的数字流与价值和计数。我能想到的最简单的方法就是使用地图,确实如此。List<NumWithValueAndCount>&nbsp;newListOfNumWithValueAndCount&nbsp;=&nbsp;Arrays.stream(sortedArrayOfNumWithValue) &nbsp;&nbsp;&nbsp;&nbsp;.map(oldNum&nbsp;->&nbsp;new&nbsp;NumWithValueAndCount(oldNum.getNum(),&nbsp;oldNum.getValue(),&nbsp;methodToGetCount())) &nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.toList());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java