Staaankey
Staaankey

Reputation: 155

Sort data from file

First of all: Sorry for my English level. I try to learn better. So, my problem is: I have a txt file and data in file like this:

  1. Hvorostovsky 8(number of songs, i dunno exactly, just for example) Russia.
  2. Chaikovsky 9(same here) Russia.

I need to sort by the number of songs from biggest to smallest or from smallest to biggest(it's doesn't matter) What did I make:

public void onMouseClick(MouseEvent mouseEvent) {
        char separator = '.';
        ArrayList<String> listOfLines = readFileInArray();
        for(String s: listOfLines){
            char maxValue = '0';
            for(int i = 0; i < s.length(); i++){
                if(s.charAt(i) == separator){
                    if(Character.getNumericValue(maxValue) < s.charAt(i + 1)){
                        maxValue = s.charAt(i + 1);
                        System.out.println(maxValue);
                    }
                }
            }
        }
    }

I have an ArrayList, that contains data from the file and I figured out how to find the number of songs in the file, but I dunno how I can sort them.

Upvotes: 0

Views: 44

Answers (1)

Most Noble Rabbit
Most Noble Rabbit

Reputation: 2776

Based on the description of the input, you can do:

 List<String> lines = Arrays.asList("Chaikovsky.9 Russia", "Hvorostovsky.8 Russia", "OtherName.21 Russia");

 List<String> sortedLines = lines.stream()
         .sorted((s1, s2) -> {
            int l1 = s1.indexOf('.') + 1;
            int l2 = s2.indexOf('.') + 1;
            int n1 = Integer.parseInt(s1.substring(l1, s1.indexOf(' ', l1)));
            int n2 = Integer.parseInt(s2.substring(l2, s2.indexOf(' ', l2)));
            return Integer.compare(n1, n2); 
         })
         .collect(Collectors.toList());

Output:

[Hvorostovsky.8 Russia, Chaikovsky.9 Russia, OtherName.21 Russia]

Upvotes: 1

Related Questions