如何将流中的元素限制为最大数量?

  • 本文关键字:最大数 元素 java
  • 更新时间 :
  • 英文 :


让我们考虑java中的以:
(a,a,b,b,b,b,a,a,a,b,c,c,c,e,c,d,d,c,c,c,c,d)k=3

我想得到以下结果(顺序无关紧要(:
(a,a,b,b,b,a,c,c,c,e,d,d,d)

因此,例如通过允许在流中k重复项来消除重复项。
如何以优雅的方式做到这一点?

您可以使用HashMap来收集每个元素的计数器:

public class Main {
public static void main(String[] args) throws Exception {
String[] inputArray = {"a", "a", "b", "b", "b", "b", "a", "a", "a", "b", "c", "c", "c", "e", "c", "d", "d", "c", "c", "c", "c", "d"};
int k = 3;
List<String> outputArray = new ArrayList<String>();
Map<String, Integer> map = new HashMap<String, Integer>();
for (String element : inputArray) {
Integer count = map.get(element);
// If the limit has not been reached
if (count == null || count < k) {
outputArray.add(element);
// Count the number of occurences
if (count == null) {
count = 1;
} else {
count++;
}
map.put(element, count);
}
}
System.out.println("Result=" + outputArray);
}
}

试试这个

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Application {
public static void main(String[] args) {
List<String> list = Arrays.asList(new String[] {
"a","a","b","b","b","b","a","a","a","b","c","c","c","e","c","d","d","c","c","c","c","d"
});
final int k = 3;
Map<String, Integer> countMap = new HashMap<>();
List<String> result = list.stream().map(item -> {
if(countMap.containsKey(item)) {
countMap.put(item, countMap.get(item) + 1);
} else {
countMap.put(item, 1);
}
return item;
}).filter(item -> countMap.containsKey(item) && countMap.get(item) <= k).collect(Collectors.toList());
System.out.println(result);
}
}
int k = 3;
Map<String, Integer> count = new HashMap<>();
String[] test = {"a","a","b","b","b","b","a","a","a","b","c","c","c","e","c","d","d","c","c","c","c","d"};
List<String> fin = Arrays.stream(test).map(ch -> {
if (count.containsKey(ch)) {
count.put(ch, count.get(ch) + 1);
} else {
count.put(ch, 1);
}
return ch;
}).filter(ch -> count.get(ch) <= k+1).collect(Collectors.toList());

最新更新