在Java中使用Array计算相同的字符串

时间:2016-12-02 19:06:04

标签: java arrays dictionary count

如何从数组中计算相同的字符串并将其写在控制台中? 项目的顺序应该与项目的第一次出现的顺序相对应。如果有两种或更多种类,请在项目名称中添加“s”。

String[] array = {"Apple","Banana","Apple","Peanut","Banana","Orange","Apple","Peanut"};

输出:

3 Apples
2 Bananas
2 Peanuts
1 Orange

我试过了:

String[] input = new String[1000];
    Scanner sIn = new Scanner(System.in);
    int counter =0;
    String inputString = "start";
    while(inputString.equals("stop")==false){
        inputString = sIn.nextLine();
        input[counter]=inputString;
        counter++;
    }
    List<String> asList = Arrays.asList(input);
    Map<String, Integer> map = new HashMap<String, Integer>();
    for (String s : input) {
        map.put(s, Collections.frequency(asList, s));
    }
    System.out.println(map);

但我不知道如何从地图中取出元素并按照我的意愿对它们进行排序。

4 个答案:

答案 0 :(得分:2)

使用Java流BEGIN DECLARE @myData VARCHAR(20) SELECT @myData = myData FROM ( SELECT myData, ROW_NUMBER() OVER (order by vw_masterView.LastDate desc) AS Rownumber FROM vw_MasterView where clientId = @clientId ) results WHERE results.Rownumber = @COUNTER IF @myData IS NOT NULL BREAK; SET @COUNTER = @COUNTER + 1 END 并将结果收集到groupingBy中,如下所示:

Map<String, Long>

答案 1 :(得分:2)

您可以使用Map来显示结果,这是一个简单的示例:

public static void main(String args[]){
    String[] array = {"Apple","Banana","Apple","Peanut","Banana","Orange","Apple","Peanut"};
    Map<String, Integer> result = new HashMap<>();
    for(String s : array){

        if(result.containsKey(s)){
            //if the map contain this key then just increment your count
            result.put(s, result.get(s)+1);
        }else{
            //else just create a new node with 1
            result.put(s, 1);
        }
    }
    System.out.println(result);
}

答案 2 :(得分:1)

Java 8允许使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="form-group"> <div class="col-md-10"> <select id="Name"> <option>Student</option> <option>Lecturer</option> </select> </div> </div> <div class="StudentSection" style="display:none;"> StudentSection Some contents </div> <div class="LecturerSection" style="display:none;"> LecturerSection Some contents </div> <script type="text/javascript"> $(document).ready(function () { $(".StudentSection").hide(); $(".LecturerSection").hide(); $("#Name").change(function () { if ($("#Name").val() == "Student") { $(".StudentSection").show(); $(".LecturerSection").hide(); } else { $(".LecturerSection").show(); $(".StudentSection").hide(); } }); }); </script>groupingBy以非常优雅的方式执行此操作。使用counting代替默认地图应该处理排序:

LinkedHashMap

答案 3 :(得分:0)

使用java 8

Map<String, Long> myMap = Stream.of(array).collect(Collectors.groupingBy(Function.identity(),                  Collectors.counting()));