How to count duplicate elements in ArrayList?

前端 未结 10 1595
悲哀的现实
悲哀的现实 2020-12-15 11:55

I need to separate and count how many values in arraylist are the same and print them according to the number of occurrences.

I\'ve got an arraylist called digits :<

10条回答
  •  忘掉有多难
    2020-12-15 12:14

    By using the Stream API for example.

    package tests;
    
    import org.junit.Assert;
    import org.junit.Test;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Map;
    import java.util.function.Function;
    import java.util.stream.Collectors;
    
    public class Duplicates {
    
        @Test
        public void duplicates() throws Exception {
            List items = Arrays.asList(1, 1, 2, 2, 2, 2);
    
            Map result = items.stream()
                    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    
            Assert.assertEquals(Long.valueOf(2), result.get(1));
            Assert.assertEquals(Long.valueOf(4), result.get(2));
        }
    }
    

提交回复
热议问题