使用Java 8在ArrayList中进行过滤、排序和查找元素。

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

Filter , Sort and Find element in a ArrayList using Java8

问题

import java.util.*;
import java.util.stream.Collectors;

public class StreamFilterSortMain {

    public static void main(String[] args) throws InterruptedException {
        List<Guid> guids = new ArrayList<>();
        guids.add(new Guid("guid1","YES",new Date()));
        Thread.sleep(1000);
        guids.add(new Guid("guid2","NO",new Date()));
        Thread.sleep(1000);
        guids.add(new Guid("guid3","YES",new Date()));
        Thread.sleep(1000);
        guids.add(new Guid("guid4","YES",new Date()));

        // Java 8 approach
        Guid pGuid = filterAndThenSortUsingJava8(guids);
        System.out.println("Guid=" + pGuid);
    }

    private static Guid filterAndThenSortUsingJava8(List<Guid> guids) {
        List<Guid> filteredGuids = guids.stream()
                .filter(guid -> guid.getActive().equals("YES"))
                .sorted(Comparator.comparing(Guid::getCreated).reversed())
                .collect(Collectors.toList());

        return filteredGuids.get(0);
    }
}

Note: The above code demonstrates how to rewrite the filterAndThenSortUsingTraditonalJava() method using Java 8 features such as streams and lambda expressions. The filter() function is used to filter out GUIDs with the active status "YES", and the sorted() function is used to sort the filtered GUIDs based on their creation dates in descending order. The result is collected into a list, and the first element (which has the latest created date) is returned as the processed GUID.

英文:

I have an List of GUIDs, from which I need to select the latest Active GUID. I wrote the code using traditional Java. I am trying to write with Java 8. Any suggestions ?

    @Getter
    @Setter
    @AllArgsConstructor
    @NoArgsConstructor
    @ToString
    public class Guid {
    
    private String guid ;

    private String active;

    private Date created ;
    }

  public class StreamFilterSortMain {

public static void main(String[] args) throws InterruptedException {

    List&lt;Guid&gt; guids = new ArrayList&lt;&gt;();
    guids.add(new Guid(&quot;guid1&quot;,&quot;YES&quot;,new Date()));
    Thread.sleep(1000);
    guids.add(new Guid(&quot;guid2&quot;,&quot;NO&quot;,new Date()));
    Thread.sleep(1000);
    guids.add(new Guid(&quot;guid3&quot;,&quot;YES&quot;,new Date()));
    Thread.sleep(1000);
    guids.add(new Guid(&quot;guid4&quot;,&quot;YES&quot;,new Date()));


    //Traditional Java
    Guid pGuid = filterAndThenSortUsingTraditonalJava(guids);
    System.out.println(&quot;Guid=&quot;+pGuid);

}

private static Guid filterAndThenSortUsingTraditonalJava(List&lt;Guid&gt; guids) {
    Guid processedGuid = null;

    //Use Iterator or Create New ArrayList
    List&lt;Guid&gt; filteredGuids = new ArrayList&lt;&gt;();
    for (Guid guid: guids) {

        if(guid.getActive().equals(&quot;YES&quot;)){
            filteredGuids.add(guid);
        }
    }

    Collections.sort(filteredGuids, new Comparator&lt;Guid&gt;() {
        @Override
        public int compare(Guid o1, Guid o2) {
            return o2.getCreated().compareTo(o1.getCreated());
        }
    });

    processedGuid = filteredGuids.get(0);

    return processedGuid;

   }


   }

How to rewrite the method using filterAndThenSortUsingTraditonalJava() using Java8 . I am pretty new to Java8. Really appreciate your suggestion.

答案1

得分: 1

希望这能满足您的需求

private static Guid filterAndThenSort(List<Guid> guids) {

    return guids
            .stream() //我们可以使用流或并行流
            .filter(guid -> guid.getActive().equals("YES")) //如果active等于YES,则过滤guid
            .sorted((guid1, guid2) -> guid2.getCreated().compareTo(guid1.getCreated())) //使用时间戳降序排序
            .findFirst() //找到第一个元素
            .orElse(null); //如果未找到元素,则返回null

}
英文:

Hope this satisfies your requirement

   private static Guid filterAndThenSort(List&lt;Guid&gt; guids) {

   return guids
            .stream() //we can use stream or parallelstream
            .filter( guid -&gt;  guid.getActive().equals(&quot;YES&quot;) ) // filters guid if active euals YES
            .sorted((guid1, guid2) -&gt; guid2.getCreated().compareTo(guid1.getCreated())) // sorting using timestamp descending
            .findFirst() // findfirst element
            .orElse(null); //if element not found return null

}

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

发表评论

匿名网友

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

确定