Lambda Java 8 - 如何在流式处理String列表时转换为Date列表

6

有没有一种方法可以在流式收集数据的同时将字符串列表(List of Strings)转换成日期列表(List of Dates)?

我的尝试:

我定义了一个SimpleDateFormat并尝试在以下代码中使用它,但我无法使其完全运行。

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.mm.yyyy");

ArrayList<Date> dateList = stringList.stream()
              .filter(s -> s.startsWith("<"))
              .collect(Collectors.toList());

解决方案

根据使用 map 的提示,我现在得到了一个可行的解决方案,看起来像这样。当然,任何对此进行优化的建议都是欢迎的!

int year = 2016;
int month = 2;
int day = 15;


final List<LocalDate> dateListEarlier = dateList.stream()
        .filter(s -> s.startsWith("<"))
        .map(s -> s.substring(1).trim())
        .map(s -> LocalDate.parse(s, formatter))
        .sorted()
        .filter(d -> d.isAfter(LocalDate.of(year, month, day)))
        .collect(Collectors.toList());

使用定义的 simpleDateFormat 实际转换您的字符串可能是个好主意。您可以过滤一些内容,就这样。这里有几个关于流中类型转换的示例。 - Tom
1
map 是你要找的。 - Tobb
3个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
10

由于您正在使用 Java8,您可以利用新的 DateTime API。

    List<String> dateStrings = Arrays.asList("12.10.2016", "13.10.2016", "14.10.2016");
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
    List<LocalDate> localDates = dateStrings.stream().map(date -> LocalDate.parse(date, formatter)).collect(Collectors.toList());
    System.out.println(localDates);

输出

[2016-10-12, 2016-10-13, 2016-10-14]

为什么这个代码对于下面的列表不起作用? - crcr

2
使用map方法。
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.mm.yyyy");

final List<Date> dateList = strings.stream()
                                   .filter(s -> s.startsWith("<"))
                                   .map(s -> { 
                                          try {
                                             simpleDateFormat.parse(s));
                                          } catch (final ParseException e) {
                                             throw new RuntimeException("Parse failed", e);
                                          }
                                    }).collect(Collectors.toList());

错误1:无法从List<Date>转换为ArrayList<Date>。 错误2:未处理的异常类型ParseException。 - Andreas
仍然无法编译。 - Andreas
toList returns List of objects not ArrayList - Saravana
这就是我抄袭 OP 的下场 ;) - Tobb

0

你所需要做的就是编写一个函数,将 String 映射到 Date 对象,如下所示:

public static void main(String[] args) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy");
    List<String> stringList = new ArrayList<>();
    stringList.add("10.10.2014");

    Function<String, Date> function = new Function<String, Date>() {

        @Override
        public Date apply(String s) {
            try {
                return simpleDateFormat.parse(s);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
    };

    List<Date> collect = stringList.stream().map(function).collect(Collectors.<Date>toList());

    System.out.println(collect);
}

1
当遇到坏数据时,返回null可能是一个不好的主意。 - Andreas
由于您正在使用Java 8功能,是否有任何原因要创建匿名类而不是lambda表达式块? - Andreas
已更正 null。此外,没有特定的原因。我只是为了可读性而喜欢匿名类。 - Darshan Mehta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,