小编Fre*_*Goo的帖子

如何在流中使用两个过滤器进行不同的转换

我只需要针对特定​​条件执行转换.我做这个转变:

// filter 1: less date - group by max date by groupId
        List<Info> listResult = new ArrayList<>(listInfo.stream()
                .filter(info -> info.getDate().getTime() < date.getTime())
                .collect(Collectors.groupingBy(Info::getGroupId, Collectors.collectingAndThen(
                        Collectors.reducing((Info i1, Info i2) -> i1.getDate().getTime() > i2.getDate().getTime() ? i1 : i2),
                        Optional::get))).values());
Run Code Online (Sandbox Code Playgroud)

但是对于超过指定日期的情况,我不需要转换任何东西,我只需要返回这些数据:

// filter 2: more date - nothing change in list
        List<Info> listMoreByDate = listInfo.stream()
                .filter(info -> info.getDate().getTime() >= date.getTime())
                .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

接下来,要结合这两个过滤器 - 我将两个列表组合在一起:

listResult.addAll(listMoreByDate);
Run Code Online (Sandbox Code Playgroud)

我的问题是,这可以在一个流中完成吗?因为过滤器2绝对没用,它只返回这个条件的列表.

是否可以通过一个连续表达式执行这些转换?

我的完整代码:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class App {
    public static …
Run Code Online (Sandbox Code Playgroud)

java java-8 java-stream

11
推荐指数
2
解决办法
447
查看次数

如何在 Spring Boot 中实现装饰模式

我知道如何在没有 Spring 的情况下实现和使用装饰器模式。

因为在这种模式中,您自己控制创建组件的过程,并且可以执行动态行为添加。

下面是一个不使用 Spring 的实现示例:

public class SimpleDecoratorApp {
    public static void main(String[] args) {
        SimplePrinter simplePrinter = new SimplePrinter();

        Printer decorated = new UpperCasePrinterDecorator(
                new AddAsterisksPrinterDecorator(simplePrinter)
        );
        decorated.print("hello");   // *** HELLO ***
    }
}

interface Printer {
    void print(String msg);
}

class SimplePrinter implements Printer {
    @Override
    public void print(String msg) {
        System.out.println(msg);
    }
}

abstract class PrinterDecorator implements Printer {
    protected Printer printer;
    public PrinterDecorator(Printer printer) {
        this.printer = printer;
    }
}

class UpperCasePrinterDecorator extends PrinterDecorator …
Run Code Online (Sandbox Code Playgroud)

java spring design-patterns spring-boot

7
推荐指数
2
解决办法
7222
查看次数

执行.max()方法时在Java流中如何增加值

我有一个在列表中具有位置值的实体。然后,您需要通过获取最后一个值并增加一个来确定下一个头寸的值。如果没有一个元素,则返回零。

public class App {
    public static void main(String[] args) {
        ArrayList<Entity> entities = new ArrayList<>();

        long nextPositionOrFirstIfNotExistWhenEmpty = getNextPositionOrFirstIfNotExist(entities);
        if (nextPositionOrFirstIfNotExistWhenEmpty != 0L) {
            throw new RuntimeException("Invalid");
        }

        entities.add(new Entity(2L));
        entities.add(new Entity(123L));
        entities.add(new Entity(3L));

        long nextPositionOrFirstIfNotExist = getNextPositionOrFirstIfNotExist(entities);
        if (nextPositionOrFirstIfNotExist != 124L) {
            throw new RuntimeException("Invalid");
        }
    }

    // how to refactoring this? not like "optionalLong.isPresent()"
    public static long getNextPositionOrFirstIfNotExist(List<Entity> entities) {
        OptionalLong optionalLong = entities.stream()
                .mapToLong(Entity::getPositionInList)
                .max();

        return optionalLong.isPresent() ? optionalLong.getAsLong() + 1 : 0L;
    }
}

class …
Run Code Online (Sandbox Code Playgroud)

java java-8 java-stream

5
推荐指数
1
解决办法
111
查看次数

如何在Java中正确实现Tree的equals()、hashCode()?

我有一个树结构,我需要重写 equals/hashCode 方法,因为我在单元测试中使用预期结果的检查。

树类型结构的问题在于它们递归地相互引用。尤其是父母对于孩子,反之亦然。

如果所有字段都在 equals/hashCode 方法中使用,则会出现循环。问题是如何正确地覆盖 then 以免违反合同。

我将举一个例子来说明我是如何实现它的。

public class App {
    public static void main(String[] args) {
        Book book1 = new Book(1L, "The catcher in the rye");
        Book book2 = new Book(2L, "Rich Dad Poor Dad");

        BookTree bookTree1 = new BookTree(book1);
        BookTree bookTreeChild1 = new BookTree(book2);
        bookTree1.addChild(bookTreeChild1);

        BookTree bookTree2 = new BookTree(book1);
        BookTree bookTreeChild2 = new BookTree(book2);
        bookTree2.addChild(bookTreeChild2);

        if (!bookTree1.equals(bookTree2)) {
            throw new RuntimeException("Invalid override equals");
        }
    }
}

class Book {
    private Long id;
    private String …
Run Code Online (Sandbox Code Playgroud)

java tree equals hashcode

5
推荐指数
1
解决办法
851
查看次数

如何使用MockMvc在响应主体中格式化Spring REST Docs

我用Spring REST Docs编写API文档。

代码示例:

@Override
public void getById(String urlTemplate, PathParametersSnippet pathParametersSnippet, Object... urlVariables) throws Exception {
    resultActions = mockMvc.perform(get(urlTemplate, urlVariables)
            .principal(principal)
            .contentType(APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(print());

    // do..
}
Run Code Online (Sandbox Code Playgroud)

但是问题是测试结果只能在一行中回答。而且,了解返回数据的结构非常困难。

响应示例:

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[application/json;charset=UTF-8]}
     Content type = application/json;charset=UTF-8
             Body = {"creator":null,"modifier":null,"modificationTime":null,"creationTime":null,"id":100,"deleted":false,"name":"Name","description":null,"report":[{"creator":"System","modifier":"System","modificationTime":"2019-01-30T14:21:50","creationTime":"2019-01-30T14:21:50","id":1,"name":"Form name","reportType":{"creator":"System","modifier":"System","modificationTime":"2019-01-30T14:21:50","creationTime":"2019-01-30T14:21:50","id":1,"deleted":false,"name":"Raport"},"unmodifiable":true}]}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
Run Code Online (Sandbox Code Playgroud)

此外,我根据收到的答案生成文档,并且在文档中还使用未格式化的JSON

我究竟做错了什么?如何启用JSON格式?

java spring spring-mvc-test spring-restdocs

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

如何使用Java中的对象正确复制集合

我有一个方法(List<Book> getListWithPrefixInName(List<Book> books)),它接受一个集合作为输入并使用每个集合对象执行一个转换。而且我不希望这些更改反映在已转移的集合上,而只是返回修改后的集合。因为我需要我的原始收藏。

因此,我认为只需创建一个新集合即可复制:

List<Book> clone = new ArrayList<>(books);
Run Code Online (Sandbox Code Playgroud)

但是我怎么错...我的代码:

public class App {

    public static final String PREFIX = "PREFIX";

    public static void main(String[] args) {
        List<Book> books = new ArrayList<>();
        books.add(Book.of(1L, "The Catcher in the Rye"));
        books.add(Book.of(2L, "The Green Mile"));
        List<Book> booksWithPrefix = getListWithPrefixInName(books);

        for (Book book : books) {
            if (book.getName().contains(PREFIX)) {
                System.out.println(String.format("original book: '%s' have been changed", book));
            }
        }
    }

    public static List<Book> getListWithPrefixInName(List<Book> books) {
        List<Book> clone = new ArrayList<>(books);  // I …
Run Code Online (Sandbox Code Playgroud)

java collections clone java-8

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