我正在编写一个代码,其中我需要计算数组中 1 的数量,现在我可以通过循环遍历数组来用旧方法来完成,但我想知道如何使用 Streams 来完成。
int[] arr = {1,2,4,1,5,1}; //example array
int oneFreq = 0;
Arrays.stream(arr).forEach(x - > {if(x==1) oneFreq++;});
Run Code Online (Sandbox Code Playgroud)
现在这会导致编译时错误:从 lambda 表达式引用的局部变量必须是最终的或有效的最终变量。
是否有任何解决方法来更新流中的局部变量?因为让它成为最终意味着那是不可能的
我有一个Optional<LocalDate>对象和一个Stream其他日期。
Stream<LocalDate> dates = ...;
Optional<LocalDate> dateOptional = ...;
Run Code Online (Sandbox Code Playgroud)
我想过滤掉可选的所有日期。如果可选项不存在,过滤器不应该做任何事情。
我写过Predicate这样的:
Predicate<LocalDate> predicate = date -> !dateOptional.isPresent() || !date.isAfter(dateOptional.get());
Stream<LocalDate> filteredStream = dates.filter(predicate);
Run Code Online (Sandbox Code Playgroud)
我想避免使用isPresent()和get()。是否有更实用的方式来编写相同的逻辑?我正在使用 Java 8。
我想总结来自例如的数字。String像 "153" 直到索引 2 并6因为 1+5=6而收到结果。在正常情况下,我会使用经典的循环解决方案,例如检查当前索引是否低于 2:
static int sum(String s){
int sum = 0;
for(int i = 0; i < s.length() ; i++){
if( Character.isDigit(s.charAt(i)) ){
sum = sum + Character.getNumericValue(s.charAt(i));
}
}
return sum;
}
Run Code Online (Sandbox Code Playgroud)
上面的方法可以正常工作,但我想将此逻辑重写为 Javastream方法。
我有一个实现,如:
public static int sumDigitsTillIndex(String number) {
return IntStream.range(0, number.length())
.filter(i -> i < 2)
.map(number::charAt)
.sum();
}
Run Code Online (Sandbox Code Playgroud)
对于这个参数 153,我收到了 102,这对我来说是一个惊喜。
我找到了另一个类似的解决方案,例如:
return String
.valueOf(number)
.chars()
.map(Character::getNumericValue)
.sum();
Run Code Online (Sandbox Code Playgroud)
这是正确地对数字求和,但使用其他filter方法,例如:
.filter(index -> number.charAt(index) < …
我想知道是否有办法使用 java 的流 API 过滤连续/互连的元素?
为您提供此问题的背景:我检索了包含不同停靠点的交通线列表。作为用户,我现在只想知道从 X 到 Y 的路线上的旅行时间和站点。所以我需要过滤所有相互连接的路段(停止 a -> 停止 b)。
我有一个未排序的对象列表,其中包含字段start和end。我现在想检索一个列表,该列表仅包含在这两个点之间逻辑连接的元素。这里有一个简单的例子:
我想过滤开始 B和结束 E
List to filter: {A,B},{B,C},{C,D},{D,E},{E,F}
List I want: {B,C},{C,D},{D,E}
Run Code Online (Sandbox Code Playgroud) 让我们假设我有一个对象 P 的列表。
Class P {
int id;
Map<String,String> value;
}
Run Code Online (Sandbox Code Playgroud)
一个值看起来像
value = {
"Category" : "Category 1",
"family" : "Family 1",
"color" : "Color 1"
}
Run Code Online (Sandbox Code Playgroud)
如上所述,我有 P 的列表。假设该列表是 listP。
map1 = {
"Category" : "Category 1",
"family" : "Family 1",
"color" : "Color 1"
}
map2 = {
"Category" : "Category 2",
"family" : "Family 2",
"color" : "Color 1"
}
map3 = {
"Category" : "Category 1",
"family" : "Family 1",
"color" : "Color 2"
} …Run Code Online (Sandbox Code Playgroud) 怎样才能Collection<Integer>转换成Spliterator.OfInt?我尝试了很多方法,但都没有奏效。我可以 :
Collection<Integer> coll = new ArrayList<>();
Spliterator<Integer> ints = coll.spliterator();
Run Code Online (Sandbox Code Playgroud)
但我想要一个Spliterator.OfInt而不是Spliterator<Integer>. 如何做到这一点?
我有以下代码:
private List<CategoryModel> getReserveStockRuleMaxPriorityNavigationCategoryModel (Collection<CategoryModel> categoryModels){
return categoryModels.stream()
.map(NavigationCategoryModel.class::cast)
.sorted(Comparator.comparing(NavigationCategoryModel::getReserveStockRuleSetCategoryPriority, Comparator.nullsLast(Comparator.reverseOrder())))
.sorted(Comparator.comparing(navigationCategoryModel -> navigationCategoryModel.getReserveStockRuleSet().getCode(),Comparator.nullsLast(Comparator.naturalOrder())))
.collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
有了这个,我的目标是进行两种排序,第一种是根据reserveStockRuleSetCategoryPriority INT 反向排序,然后将具有reserveStock.code 属性为null 的NavigationCategoryModel 放在列表的末尾。
但是,我收到了 NPE,因为在此类别列表中,我可以接收 NavigationCategoryModels,其属性 ReserveStockRuleSet 为 null 。
我不想过滤和排除排序中为空的那些,因为我想将它们放在列表的末尾
一个示例输入是:
NavCatModel priority : 500 , null reserveStockRuleSet
NavCatModel priority : 100 , NOT NULL reserveStockRuleSet
NavCatModel priority : 300 , null reserveStockRuleSet
NavCatModel priority : 200 , NOT NULL reserveStockRuleSet
Run Code Online (Sandbox Code Playgroud)
两种排序后的预期结果:
NavCatModel priority : 200 , NOT NULL reserveStockRuleSet
NavCatModel priority : 100 , NOT NULL reserveStockRuleSet
NavCatModel priority …Run Code Online (Sandbox Code Playgroud) 有没有办法根据属性的值将对象列表转换为字符串列表?我有一个实体标签
public class Tag {
private int tagID;
private String description;
}
Run Code Online (Sandbox Code Playgroud)
我得到一个带有 ID 和描述的标签列表:
[Tag [tagID=1, description=121], Tag [tagID=1, description=244], Tag [tagID=1, description=331], Tag [tagID=2, description=244], Tag [tagID=2, description=122]]
Run Code Online (Sandbox Code Playgroud)
我需要的是:
List<String> output = ["121,244,331", "244,122"]
Run Code Online (Sandbox Code Playgroud)
到目前为止,我把这个放在一起:
String description = tags.stream().map(Tag::getDescription).collect(Collectors.joining( ";" ));
Run Code Online (Sandbox Code Playgroud)
输出一个标签的结果
String description = "121,244,331"
Run Code Online (Sandbox Code Playgroud)
当然,我可以通过循环运行它并将结果附加到数组中,但我想知道是否有更优雅的方式 - 甚至是单行?
迭代 aMap<Integer, List<String>>并转换为 type List<KeyPair>。在 java 8 (Using streams) 中任何更好的方法来做到这一点。
幼稚的方式:
final List<KeyPair> keyPairs = Lists.newArrayList();
for (final Map.Entry<Integer, List<String>> entry : map.entrySet()) {
for (final String value : entry.getValue()) {
keyPairs.add(new KeyPair()
.withHashKey(value)
.withRangeKey(entry.getKey()));
}
}
Run Code Online (Sandbox Code Playgroud) 我需要在每次出现特定元素之前添加一个元素。我可以使用 for 循环执行此操作并计算索引,然后添加元素。有没有不使用 for 循环或使用流的有效方法。
例如:在每次出现 2 之前int[] a = {1,2,4,5,7,9,2,5}
添加元素{3},导致{1,3,2,4,5,7,9,3,2,5}
试图:
int[] a = {1, 2, 4, 5, 7, 9, 2, 5};
int[] new1 = null;
int[] indexToAdd = IntStream.range(0, a.length)
.filter(i -> a[i] == 2)
.map(i -> i)
.toArray();
for(int j = 0; j<indexToAdd.length; j++){
final Integer innerj = new Integer(j);
new1 = IntStream.range(0,a.length)
.map(i -> {
if (i < indexToAdd[innerj]) {
return a[i];
} else if (i == indexToAdd[innerj]) {
return 3 …Run Code Online (Sandbox Code Playgroud) java ×10
java-stream ×10
java-8 ×3
hashmap ×2
arrays ×1
collections ×1
collectors ×1
comparator ×1
java-11 ×1
lambda ×1
loops ×1
optional ×1
performance ×1
predicate ×1
sorting ×1