Marios Nikolaou
Marios Nikolaou

Reputation: 1336

Pairs of values and sort using the first one java

I have a big file with pairs of values and I want to sort them based on the first value. For example

  1,2
  3,4
  1,3
  5,2
  1,5

And I want to sort them based on the first value.How will I do that?

Upvotes: 0

Views: 288

Answers (2)

Ousmane D.
Ousmane D.

Reputation: 56433

Assuming you've done all the boilerplate code for reading the file and storing it into some type of collection. you can then sort your collection based on the first value of each string.

TreeSet<String> resultSet = myCollection.parallelStream().sorted(
            Comparator.comparingInt((String e) -> Integer.parseInt(e.substring(0,e.indexOf(",")))))
            .collect(Collectors.toCollection(TreeSet::new));

note - ensure you've trimmed all the whitespace from each string when reading the file before accumulating it into your temporary collection or if you want, you can trim it before the e.substring call i.e e.trim().substring(0,e.indexOf(","))).

edit

The above solution assumes that each string within myCollection could have more than 1 digit before or after the delimiter ,. However, assuming there will always be 1 digit before and after the , delimiter you need not sort any data rather use a TreeSet as the accumulator collection when reading the file instead of a HashSet because it will sort the data as you're adding string objects to the collection.

Upvotes: 1

Mafalda Hopkirk
Mafalda Hopkirk

Reputation: 31

Well, i don't know much, but i suggest a while/for loop that reads each pair (num1, num2) and if (num1>num2){num1 now has the value of num2, and vice versa}. This would order the pairs. Now, I suggest another for/while loop that goes through the first number of each pair, and apllies a sorting algorithm such as:

for(int i = 0; i<= numberOfPairs; i++){
    int number = firstOfPair[i];
    for(int j = i; j<=(numberOfPairs-i; j++){
        if(firstOfPair[j] > number){
           auciliarVariable = firstOfPair[j];
           firstOfPair[j] = firstOfPair[i];
           firstOfPair[i] = auxiliarVariable;
         }
    }
}

Upvotes: 0

Related Questions