小编Ami*_*toj的帖子

Java流减少

我有以下示例数据集,我想根据方向的值使用Java流api进行转换/缩减

Direction    int[]
IN           1, 2
OUT          3, 4
OUT          5, 6, 7
IN           8
IN           9
IN           10, 11
OUT          12, 13
IN           14
Run Code Online (Sandbox Code Playgroud)

Direction    int[]
IN           1, 2, 
OUT          3, 4, 5, 6, 7
IN           8, 9, 10, 11
OUT          12, 13
IN           14
Run Code Online (Sandbox Code Playgroud)

到目前为止我写的代码

enum Direction { IN, OUT }

class Tuple {
  Direction direction;
  int[] data;

  public Tuple merge(Tuple t) {
      return new Tuple(direction, concat(getData(), t.getData()));
  }
}

private static int[] concat(int[] first, int[] second) …
Run Code Online (Sandbox Code Playgroud)

java reduce java-8 java-stream

10
推荐指数
1
解决办法
589
查看次数

Java 8 - 从List中删除重复的元素序列

我有一个要求,我想使用Java Stream Api处理来自系统的事件流并应用数据清理过程来删除重复的事件.这是按顺序多次重复删除相同的事件,而不是创建不同事件的列表.大多数在线可用的Java Stream api示例都是从给定输入创建不同的输出.

例如,输入流

[a,b,c,a,a,a,a,d,d,d,c,c,e,e,e,e,e,e,f,f,f]

输出列表或流应该是

[a,b,c,a,d,c,e,f]

我当前的实现(不使用Stream api)看起来像

public class Test {
    public static void main(String[] args) {
        String fileName = "src/main/resources/test.log";
        try {
            List<String> list = Files.readAllLines(Paths.get(fileName));
            LinkedList<String> acc = new LinkedList<>();

            for (String line: list) {
                if (acc.isEmpty())
                    acc.add(line);
                else if (! line.equals(acc.getLast()) )
                    acc.add(line);
            }

            System.out.println(list);
            System.out.println(acc);

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出,

[a, b, c, a, a, a, a, d, d, d, c, c, e, e, e, e, e, …
Run Code Online (Sandbox Code Playgroud)

java java-8 java-stream

9
推荐指数
1
解决办法
1873
查看次数

使用Collectors.toMap或groupingBy收集Map中地图操作的结果

我有一个类型列表,List<A>并且通过map操作获得了List<B>所有A元素合并到一个列表中的类型的集合列表。

List<A> listofA = [A1, A2, A3, A4, A5, ...]

List<B> listofB = listofA.stream()
  .map(a -> repo.getListofB(a))
  .flatMap(Collection::stream)
  .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

没有平面图

List<List<B>> listOflistofB = listofA.stream()
  .map(a -> repo.getListofB(a))
  .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

我想将结果收集为类型图,Map<A, List<B>>到目前为止,我尝试使用各种Collectors.toMapCollectors.groupingBy选项,但无法获得所需的结果。

java lambda java-8 java-stream collectors

8
推荐指数
1
解决办法
155
查看次数

标签 统计

java ×3

java-8 ×3

java-stream ×3

collectors ×1

lambda ×1

reduce ×1