ArrayList, to re-count the number of duplicate data occurs

  • HashSet

1.HashSet not on the same element, it can be removed using the List repeating elements, but does not guarantee the order of the data.

        List<String> beforeList = new ArrayList<String>();       

        beforeList.add("sun");

        beforeList.add("star");

        beforeList.add("moon");

        

        Set<String> middleHashSet = new HashSet<String>(beforeList);

        

        List<String> afterHashSetList = new ArrayList<String>(middleHashSet);

2.LinkedHashSet not on the same element, but also to guarantee the order.

       List<String> beforeList = new ArrayList<String>();

        

        beforeList.add("sun");

        beforeList.add("star");

        beforeList.add("moon");

        

        Set<String> middleLinkedHashSet = new LinkedHashSet<String>(beforeList);

        

        List<String> afterHashSetList = new ArrayList<String>(middleLinkedHashSet);

 

  • Stream

List of de-heavy in JDK1.8 in the Stream

list.stream().distinct();

First, get this list of Stream. Then call the distinct () method.

java8 manner provided in the flow data is processed, is very fast, with the underlying framework forkJoin provide parallel processing, a plurality of processors such that data streams processed simultaneously, so a very short time-consuming.

List<String> list = Arrays.asList("AA", "BB", "CC", "BB", "CC", "AA", "AA","DD");

        long l = list.stream().distinct().count();

        System.out.println ( "number of unique data:" + l);

        String output = list.stream().distinct().collect(Collectors.joining(","));

        System.out.println(output);

list.stream().distinct().forEach(System.out::println);

 

Data is the number of unique: 4

AA,BB,CC,DD

AA

BB

CC

DD

But the set of entity classes can not be de-emphasis.

List<Test> list2 = new ArrayList<Test>();{

            list2.add(new Test(1, "123"));

            list2.add(new Test(2, "123"));

            list2.add(new Test(3, "789"));

            list2.add(new Test(4, "456"));

            list2.add(new Test(5, "123"));

        }

        long l2 = list2.stream().distinct().count();

        System.out.println("No. of distinct Test:"+l2);

        list2.stream().distinct().forEach(b -> System.out.println(b.getId()+ "," + b.getName()));

 

No. of distinct Test:5

1,123

2,123

3,789

4,456

5,123

 

发布了21 篇原创文章 · 获赞 0 · 访问量 2274

Guess you like

Origin blog.csdn.net/hfaflanf/article/details/101701195