标签: java-stream

使用 Java Stream API 进行分层过滤

我有一些命令式 Java 条件代码,我想对其进行重构以使用 Streams。

具体来说,我有这张地图,我想根据特定的过滤条件过滤到一个列表中。

private  Map<Integer,Thing> thingMap = new HashMap<Integer,Thing>();
// populate thingMap
Run Code Online (Sandbox Code Playgroud)

这是使用它的代码:

List<Thing> things = new ArrayList<Thing>();

for (Thing thing : thingMap.values()) {
    if (thing.getCategory().equals(category)) {
        if (location == null) {
            things.add(thing);
        } else if (thing.getLocation().equals(location)) {
            things.add(thing);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我将其重构为以下内容。但是缺少的是我希望只有在类别过滤器通过时才检查位置。另外,我怀疑有更好的方法来做到这一点:

List<Thing> things = thingMap.entrySet()
                      .stream()
                      .filter(t -> t.getValue().getCategory().equals(category))
                      .filter(t -> 
                          location == null || 
                          t.getValue().getLocation().equals(location)
                       )
                      .map(Map.Entry::getValue)
                      .collect(Collectors.toList());
    
Run Code Online (Sandbox Code Playgroud)

使用 Streams 保留分层条件检查的惯用方法是什么?

java java-stream

2
推荐指数
1
解决办法
70
查看次数

How can I find the number of lines that contain a certain word in java using Java Stream?

My method would read from a text file and find the word "the" inside of each line and count how many lines contain the word. My method does work but the issue is that I need only lines that contain the word by itself, not a substring of the word as well

For example, I wouldn't want "therefore" even though it contains "the" it's not by itself.

I'm trying to find a way to limit the lines to those that …

java java-stream

2
推荐指数
1
解决办法
58
查看次数

两个流将 flatMap 设置为整数

final Set<Integer> set1 = new HashSet<>();
final Set<Integer> set2 = new HashSet<>();

Stream.of(set1, set2).mapToInt(???).forEach(intValue -> code)
Run Code Online (Sandbox Code Playgroud)

我有 2 组整数和一个流,但我想将它们全部映射到整数中。我找不到使用 maptoInt 或 flatMap 的方法,因此我可以提取两个集合的所有整数。

java java-stream

2
推荐指数
1
解决办法
106
查看次数

如何将对象列表转换为&lt;String, List&lt;String&gt;&gt; 的映射?

我有一个用户列表

Collection<User> userList = groupManager.getUserList(groupName);

不太了解 Java-Streams API,我想将它们映射到一个映射中,如下所示:键是用户键,值是用户对象的其他属性的列表。

Map<String, List<String>> userDsiplayData = userList.stream()
     .collect(Collectors.toMap(User::getKey, **.......**))
Run Code Online (Sandbox Code Playgroud)

我试图用Arrays.asList(User::getUsername(), User::getDisplayName(), User::getEmail())或类似的结构替换 **..... **但我似乎无法让它工作。

java java-stream

2
推荐指数
1
解决办法
71
查看次数

java的chars()流如何与reduce一起工作?它使用字符编码吗?

代码战争的挑战在于计算你必须将 Long 的各个整数相乘多少次才能成为一位数。例如

39 -> 3 * 9 = 27 -> 2 * 7 = 14 -> 1 * 4 = 4 // 答案是 3

这是已发布的解决方案之一 -

class Persist {
  public static int persistence(long n) {
    int times = 0;
    while (n >= 10) {
      n = Long.toString(n).chars().reduce(1, (r, i) -> r * (i - '0'));
      times++;
    }
    return times;
  }
}
Run Code Online (Sandbox Code Playgroud)

我对代码的“(i - '0')”部分感到非常困惑。我昨天才知道 Java 的 chars() 方法返回一个 IntStream 表示字符,所以立即使用 reduce 对我来说很有意义。但随后它减去了一个让我失望的字符,因为它似乎适用于它正在使用字符,但是它们是如何相乘的?

我复制了上面的代码,然后删除了字符减法,所以这是我理解的一个简单的reduce语句,也就是

n = Long.toString(n).chars().reduce(1, (r, i) -> …
Run Code Online (Sandbox Code Playgroud)

java char java-stream

2
推荐指数
1
解决办法
100
查看次数

如何使用流将地图值聚合到集合中

是否有一些简单的方法如何转换Map<Key, List<Value>>为Set<Value>获取一组嵌套在地图中的所有唯一元素?我知道这应该可以使用,reduce或者flatmap我正在努力寻找正确的组合。

我知道我可以使用 for 循环执行此操作,但我想使用流执行此操作。

java java-stream

2
推荐指数
1
解决办法
63
查看次数

处理对 java.lang.Number 的子类的操作的通用通用方法

我有一个类MyGen,它接受两个通用参数并有一个方法getValue()

public interface MyGen<E,T> {

    T getValue();
}
Run Code Online (Sandbox Code Playgroud)

通常第二个泛型类型是Longor Integer。

然后,当第二个泛型类型Long如下时,我写了一个方法来组合对象:

public static <E extends MyGen<?, Long>> long combineValue(Set<E> set) {
    return set.stream()
              .map(MyGen::getValue)
              .reduce(0L, (a,b) -> a | b);
}
Run Code Online (Sandbox Code Playgroud)

现在我想在第二种类型是Integer. 所以我尝试将上述相同的方法更新为:

public static <E extends MyGen<?, ? extends Number>> long combineValue(Set<E> set) {
    return (long) set.stream()
                     .map(MyGen::getValue)
                     .reduce((a,b) -> a | b) // error1
                     .orElse(0); // error2

}
Run Code Online (Sandbox Code Playgroud)

但显示以下错误:

  1. 错误1

运营商 | 未定义参数类型 capture#4-of ?扩展 java.lang.Number, capture#4-of ? …

java generics java-stream

2
推荐指数
1
解决办法
49
查看次数

检查字符串是否包含数组中的字符

我想检查作为文件名的字符串包含来自ILLEGAL_CHARACTERS. 只是我可以使用 for 循环,但我想通过Streams来做到这一点。

我的代码:

package shared;

import java.util.Arrays;

public class Validator {
    private static final Character[] ILLEGAL_CHARACTERS =
            {'/','\n','\r','\t','\0','\f','`','?','*','\\','<','>','|','\"',':'};

    public static boolean fileNameIsValid(String fileName) {
        return Arrays.stream(ILLEGAL_CHARACTERS).anyMatch(fileName::contains);
    }
}
Run Code Online (Sandbox Code Playgroud)

问题在于 contains 方法因为它需要一个CharSequence而不是char. 有没有办法通过流来做到这一点而不将Character[]类型更改为String[]?

java string contains character java-stream

2
推荐指数
1
解决办法
234
查看次数

使用 Java 8 迭代 Map&lt;String,Object&gt; 数组并返回 Map&lt;Long,Long&gt;

我有一个地图数组。其中我需要做一些计算并返回另一个 Map 并将相同的键计数添加到结果中的值中。我试过下面的一个。但由于它是并行运行的,因此不会添加它。

请帮助改进它

我可以在正常的 for 循环中实现这一点。

public Map<Long,Long> solve(Map<String,Stats>... map){
        Map<Long,Long> resultCount = new HashMap<Long,Long>();
        if(map != null){
       
            resultCount = Arrays.stream(map).filter(Objects::nonNull).map(map -> getUserCountMap(map))
            .collect(HashMap::new, Map::putAll, Map::putAll);
  
    }
        return resultCount;
    }
    
   public Map<Long,Long>  getUserCountMap(Map<String, Stats> map) {
       Map<Long,Long> resultCount = new HashMap<Long,Long>();
       
       map.forEach((k,v)->{
           try {
                
               String key = (String) k;
               Stats userValue = (Stats) v;
               Long userId = new Long(key);
               System.out.println("key :::"+key+":::"+resultCount.getOrDefault(userId, 0l));
               Optional<Long> count = userValue.getCount();
               System.out.println(count.get());
               count.ifPresent(aLong -> resultCount.put(userId, (resultCount.getOrDefault(userId, 0l) + aLong)));
               System.out.println(resultCount);

           } catch (Exception e) …
Run Code Online (Sandbox Code Playgroud)

java lambda java-8 java-stream

2
推荐指数
1
解决办法
474
查看次数

正则表达式一行来提取模式匹配组

使用 Java 11 我想知道如何使用 Stream API 将所有组匹配提取到单行中的字符串列表中。

鉴于此正则表达式和字符串:

String regexp = "(\\d\\d\\d)-(\\d)-(\\d\\d)";
String str = "123-8-90";
Run Code Online (Sandbox Code Playgroud)

我知道如何在多行中获得结果:

Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(str);

List<String> matches = new ArrayList<>();
if (matcher.find()) {
  matches.add(matcher.group(1));
  matches.add(matcher.group(2));
  matches.add(matcher.group(3));
}

System.out.println(matches);
Run Code Online (Sandbox Code Playgroud)

这将打印 3 个不同数字字符串的预期列表: [123, 8, 90]

我试图在一个班轮中实现相同的目标:

List<String> matches = Pattern.compile(regexp)
    .matcher(str)
    .results()
    .map(MatchResult::group)
    .collect(Collectors.toList());

System.out.println(matches);
Run Code Online (Sandbox Code Playgroud)

这会打印出意外:[123-8-90]

如何在流中使用 MatchResult::group(int) 方法?

java regex java-stream

2
推荐指数
1
解决办法
135
查看次数

标签 统计

java ×10

java-stream ×10

char ×1

character ×1

contains ×1

generics ×1

java-8 ×1

lambda ×1

regex ×1

string ×1