有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java最少重复/在数组中出现一次的项

我正在尝试打印唯一项、重复次数最多的项和重复次数最少的项,即一个数组只出现一次。在重复最少的部分,我没有得到任何输出,因为标志被设置为1,而不是预期的0

样本输入:

10
watch
laptop
iphone
watch
car
headset
laptop
watch
shoe
mobile

样本输出:

The unique items are
watch
laptop
iphone
car
headset
shoe
mobile
The maximum purchased item(s) are
watch
The minimum purchased item(s) are
iphone
car
headset
shoe
mobile 
import java.util.Arrays;
import java.text.ParseException;
import java.util.*;
import java.util.Scanner;
import java.util.ArrayList;

public class ItemDetails {
    public static void main(String[] args) {
        Scanner sn = new Scanner(System.in);
        int flag=0, flag1=0, count = 0, count1 = 0, count2 = 0;
        String maxname = null;
        int k;
//      String[] max = new String[k];
        Integer x = sn.nextInt();

        sn.nextLine(); 
        String[] names=new String[x];
        for (int i = 0; i<x; i++)
        {
            names[i] = sn.nextLine();
        }
        System.out.println("The unique items are");
        {
            for (int i = 0; i < x; i++) {
                for (int j = i+1 ; j < x; j++) 
                {
                        if (names[i].equals(names[j]))
                        { 
                    // got the unique element 
                            flag = 0;
                            break;
                        }
                        else 
                        {
                            flag = 1;
//                          break;
                        }
//                  break;
                }
                if (flag==1)
                {
                    ++count;
                    System.out.println(names[i]);

                }
            }
            System.out.println(count);  
        }
        System.out.println("The maximum purchased item(s) are");
        {
            for (int i = 0; i < x; i++) {
                for (int j = i+1 ; j < x; j++) 
                {
                    if (names[i].equals(names[j]))
                    {
                        count1++;
                        maxname = names[i];
                    }
                    else
                    {
                        count1 = 0;
                    }
                }

            }
            System.out.println(maxname);    
        }

        System.out.println("The minimum purchased item(s) are");
        {
            for (int i = 0; i < x; i++) {
                for (int j = i+1 ; j < x; j++) 
                {
                    if (names[i].equals(names[j]))
                    {
                        flag1 = 1;
                        break;
                    }
                }

                if (flag1==0)
                {
                    count2++;
                    System.out.println(names[i]);
                }
            }
            //System.out.println(maxname);  
        }
    }
}

共 (3) 个答案

  1. # 1 楼答案

    检索唯一项目:

    public static Set<String> getUniqueItems(Collection<String> items) {
        return new HashSet<>(items);
    }
    

    使用给定的Function(使用Streams)检索购买的物品:

    private static Set<String> getPurchasedItems(Collection<String> items, Function<Collection<Long>, Long> function) {
        Map<String, Long> map = items.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        final long count = function.apply(map.values());
    
        return map.entrySet().stream()
                  .filter(entry -> entry.getValue() == count)
                  .map(Map.Entry::getKey)
                  .collect(Collectors.toSet());
    }
    

    使用给定的Function(使用POJO)检索购买的物品:

    private static Set<String> getPurchasedItems(Collection<String> items, Function<Collection<Long>, Long> function) {
        Map<String, Long> map = new HashMap<>();
    
        for (String item : items)
            map.compute(item, (key, count) -> Optional.ofNullable(count).orElse(0L) + 1);
    
        final long count = function.apply(map.values());
    
        Set<String> res = new HashSet<>();
    
        for (Map.Entry<String, Long> entry : map.entrySet())
            if (entry.getValue() == count)
                res.add(entry.getKey());
    
        return res;
    }
    

    检索最大购买量:

    public static Set<String> getMaximumPurchasedItems(Collection<String> items) {
        return getPurchasedItems(items, Collections::max);
    }
    

    检索最低购买物品:

    public static Set<String> getMinimumPurchasedItems(Collection<String> items) {
        return getPurchasedItems(items, Collections::min);
    }
    
  2. # 2 楼答案

    @Alan 使用Java streams可能会简单得多,例如:

        List<String> items = new ArrayList<String>();
        // Fill List items with your data
    
        Map<String, Long> processed =items.stream()
                .collect(Collectors.groupingBy(
                                Function.identity(), Collectors.counting())                        
        );
    
        System.out.println ("Distinct items");
        processed.keySet().stream().forEach(item -> System.out.println(item));
    
        Long minCount = Collections.min(processed.values());
        Long maxCount = Collections.max(processed.values());
    
        System.out.println ("Least repeated items");
        processed.entrySet().stream().filter(entry -> entry.getValue().equals(minCount)).forEach(item -> System.out.println(item));        
    
        System.out.println ("Most repeated items");
        processed.entrySet().stream().filter(entry -> entry.getValue().equals(maxCount)).forEach(item -> System.out.println(item));
    
  3. # 3 楼答案

    在最小值的代码位置,在第二个循环之前设置flag1=0;,还应该对数组进行排序,以便能够应用此算法。除此之外,您还需要将项目与之前进行比较,以确保算法正常工作

        System.out.println("The minimum purchased item(s) are");
        {
            Arrays.sort(names);
            for (int i = 0; i < x-1; i++) {
                flag1 = 0;
                for (int j = i + 1; j < x; j++) {
                    if (names[i].equals(names[j]) || (i>1 && names[i].equals(names[i-1])) ) {
                        flag1 = 1;
                        break;
                    }
                }
    
                if (flag1 == 0) {
                    count2++;
                    System.out.println(names[i]);
                }
            }
        }