如何在Java中对列表中的值进行筛选。

huangapple go评论84阅读模式
英文:

How to filter value in list in java

问题

以下是翻译好的部分:

我们在ArrayList中有一些bean值。如何筛选,以下是包含在ArrayList中的示例。

List = [number ABCEFG, EndDATE 2020-03-01], [number ABCEFG, EndDATE 2020-04-01], [number KLMNOP, EndDATE 2020-04-01]

筛选条件是从使用Java 1.5到1.8的ArrayList中获取编号(ABCEFG)的最近的Endate。

筛选完成后的输出应为:

List = [number ABCEFG, EndDATE 2020-04-01], [number KLMNOP, EndDATE 2020-04-01]

不知道如何开始,所以没有尝试任何代码。

英文:

we have beans values in ArrayList. how do we filter below is sample of ArrayList contains.

   List =  [number ABCEFG , EndDATE  2020-03-01],[number ABCEFG , EndDATE 2020-04-01],[number KLMNOP , EndDATE 2020-04-01]

Condition to filter get recent endate for number(ABCEFG) from arraylist using java 1.5 to 1.8<br/>

After filter is done Output should be<br/>

 List =[number ABCEFG ,EndDATE 2020-04-01],[number KLMNOP ,EndDATE 2020-04-01]

No idea how to start so did not try any code

答案1

得分: 1

你可以使用Java 1.8的流式API。在流式API中,您可以使用筛选器,在筛选器中,您可以编写自己的结束日期条件逻辑,并收集集合进行返回。

List<Object> collect = list.stream()
                .filter(x -> x.getEndDate() /*在这里添加您的条件*/)
                .collect(Collectors.toList());

如果您想根据结束日期对列表进行排序,可以使用排序:

list.stream().sorted(Comparator.comparing(Object::getEndDate))
英文:

you can use java 1.8 streaming API. In streaming API you can use filter in which you can write your own condition logic on enddate and collect the collection to return.

List&lt;Object&gt; collect = list.stream()
                .filter(x -&gt; x.getEndDate() /*add your condition here*/)
                .collect(Collectors.toList());

If you want to sort list based on end date you can use sort

   stream().sorted(Comparator.comparingDate(Object::getEndDate))

P.S.: I have not provided exact code, objective is user should get hint to solve problem by themselve.

huangapple
  • 本文由 发表于 2020年10月23日 17:22:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/64497364.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定