Jave Code Examples for 'sort by value'

60 Jave code examples are found related to "sort by value". These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Project: bistoury   Author: qunarcorp   File: ProfilerDataDumper.java    License: GNU General Public License v3.0 7 votes vote down vote up
private List<Map.Entry<Integer, Long>> sortByValue(Map<Integer, Long> countMap) {
    List<Map.Entry<Integer, Long>> countEntryList = new ArrayList<>(countMap.entrySet());
    Collections.sort(countEntryList, new Comparator<Map.Entry<Integer, Long>>() {
        @Override
        public int compare(Map.Entry<Integer, Long> l, Map.Entry<Integer, Long> r) {
            long left = l.getValue();
            long right = r.getValue();
            if (left > right) {
                return -1;
            } else if (left == right) {
                return 0;
            }
            return 1;
        }
    });
    return countEntryList;
}
 
Example 2
Project: FuzzDroid   Author: srasthofer   File: MapUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(
		Map<K, V> map) {
	List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(
			map.entrySet());
	Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
		public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
			return -(o1.getValue()).compareTo(o2.getValue());
		}
	});

	Map<K, V> result = new LinkedHashMap<K, V>();
	for (Map.Entry<K, V> entry : list) {
		result.put(entry.getKey(), entry.getValue());
	}
	return result;
}
 
Example 3
Project: TagRec   Author: learning-layers   File: MapUtil.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map )
{
    List<Map.Entry<K, V>> list =
        new LinkedList<Map.Entry<K, V>>( map.entrySet() );
    Collections.sort( list, new Comparator<Map.Entry<K, V>>()
    {
        public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 )
        {
            return -(o1.getValue()).compareTo( o2.getValue() );
        }
    } );

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list)
    {
        result.put( entry.getKey(), entry.getValue() );
    }
    return result;
}
 
Example 4
Project: ctgi   Author: dineshappavoo   File: ArrangeStringsBasedOnOccurances.java    License: MIT License 6 votes vote down vote up
public static  Map<String,Integer> sortByValue(Map<String,Integer> unsortMap) {

		List<String> l = new LinkedList(unsortMap.entrySet());

		Collections.sort(l, new Comparator() {
			public int compare(Object Obj1, Object Obj2) {
				return ((Comparable) ((Map.Entry) (Obj1)).getValue())
						.compareTo(((Map.Entry) (Obj2)).getValue());
			}
		});

		Map mapSorted = new LinkedHashMap();
		for (Iterator itrerator = l.iterator(); itrerator.hasNext();) {
			Map.Entry ent = (Map.Entry) itrerator.next();
			mapSorted.put(ent.getKey(), ent.getValue());
		}
		return mapSorted;
	}
 
Example 5
Project: hugegraph-common   Author: hugegraph   File: CollectionUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMapSortByIntegerValue() {
    Map<String, Integer> unordered = new HashMap<>();
    unordered.put("A", 4);
    unordered.put("B", 2);
    unordered.put("C", 5);
    unordered.put("D", 1);
    unordered.put("E", 3);

    Map<String, Integer> incrOrdered = CollectionUtil.sortByValue(unordered,
                                                                  true);
    Assert.assertEquals(ImmutableList.of(1, 2, 3, 4, 5),
                        ImmutableList.copyOf(incrOrdered.values()));

    Map<String, Integer> decrOrdered = CollectionUtil.sortByValue(unordered,
                                                                  false);
    Assert.assertEquals(ImmutableList.of(5, 4, 3, 2, 1),
                        ImmutableList.copyOf(decrOrdered.values()));
}
 
Example 6
Project: ambiverse-nlu   Author: ambiverse-nlu   File: CollectionUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static <K, V extends Comparable<? super V>> LinkedHashMap<K, V> sortMapByValue(Map<K, V> map, final boolean descending) {
  List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
  Collections.sort(list, new Comparator<Map.Entry<K, V>>() {

    public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
      int comp = (o1.getValue()).compareTo(o2.getValue());

      if (descending) {
        comp = comp * (-1);
      }

      return comp;
    }
  });

  LinkedHashMap<K, V> result = new LinkedHashMap<K, V>();
  for (Map.Entry<K, V> entry : list) {
    result.put(entry.getKey(), entry.getValue());
  }
  return result;
}
 
Example 7
Project: quaerite   Author: mitre   File: MapUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static <K extends Comparable<? super K>,
        V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map ) {
    List<Map.Entry<K, V>> list =
            new LinkedList<>( map.entrySet() );
    Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
        @Override
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2 )
        {
            int c =  o1.getValue().compareTo(o2.getValue());
            if (c == 0) {
                return o1.getKey().compareTo(o2.getKey());
            }
            return c;
        }
    } );

    Map<K, V> result = new LinkedHashMap<>();
    for (Map.Entry<K, V> entry : list)
    {
        result.put( entry.getKey(), entry.getValue() );
    }
    return result;
}
 
Example 8
Project: quaerite   Author: mitre   File: MapUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static <K extends Comparable<? super K>,
        V extends Comparable<? super V>> Map<K, V> sortByDescendingValue(Map<K, V> map ) {
    List<Map.Entry<K, V>> list =
            new LinkedList<>( map.entrySet() );
    Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
        @Override
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2 )
        {
            int c =  o2.getValue().compareTo(o1.getValue());
            if (c == 0) {
                return o1.getKey().compareTo(o2.getKey());
            }
            return c;
        }
    } );

    Map<K, V> result = new LinkedHashMap<>();
    for (Map.Entry<K, V> entry : list)
    {
        result.put( entry.getKey(), entry.getValue() );
    }
    return result;
}
 
Example 9
Project: gemfirexd-oss   Author: gemxd   File: Misc.java    License: Apache License 2.0 6 votes vote down vote up
public static TreeSet<Map.Entry<Integer, Long>> sortByValue(
    Map<Integer, Long> distribution) {
  TreeSet<Map.Entry<Integer, Long>> entriesByVal = new TreeSet<Map.Entry<Integer, Long>>(
      new Comparator<Map.Entry<Integer, Long>>() {
        @Override
        public int compare(Entry<Integer, Long> o1, Entry<Integer, Long> o2) {
          int i;
          // order descending....
          return (i = o2.getValue().compareTo(o1.getValue())) != 0 ? i : o2
              .getKey().compareTo(o1.getKey());
        }
      });

  for (Map.Entry<Integer, Long> e : distribution.entrySet()) {
    entriesByVal.add(new GemFireXDUtils.Pair<Integer, Long>(e.getKey(), e
        .getValue()));
  }
  return entriesByVal;
}
 
Example 10
Project: alfresco-core   Author: Alfresco   File: CollectionUtils.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new sorted map, based on the values from the given map and Comparator.
 * 
 * @param map the map which needs to be sorted
 * @param valueComparator the Comparator
 * @return a new sorted map
 */
public static <K, V> Map<K, V> sortMapByValue(Map<K, V> map, Comparator<Entry<K, V>> valueComparator)
{
    if (map == null)
    {
        return Collections.emptyMap();
    }

    List<Entry<K, V>> entriesList = new LinkedList<>(map.entrySet());

    // Sort based on the map's values
    Collections.sort(entriesList, valueComparator);

    Map<K, V> orderedMap = new LinkedHashMap<>(entriesList.size());
    for (Entry<K, V> entry : entriesList)
    {
        orderedMap.put(entry.getKey(), entry.getValue());
    }
    return orderedMap;
}
 
Example 11
@Test public void sortMapsByValue() throws Exception
{
    final Map<String, Integer> expectedSorting = getNerdsSortedByBirthDate();
    
    Comparator<Integer> valueComparator = new Comparator<Integer>()
            {
                @Override public int compare(Integer i1, Integer i2)
                {
                    return i1.intValue() - i2.intValue();
                }
            };
    
    Comparator<Entry<String, Integer>> entryComparator = CollectionUtils.<String, Integer>toEntryComparator(valueComparator);
    
    final Map<String, Integer> actualSorting = CollectionUtils.sortMapByValue(nerdsBirthdays, entryComparator);
    
    assertEquals(expectedSorting, actualSorting);
}
 
Example 12
Project: examples   Author: dtpublic   File: TopNAccounts.java    License: Apache License 2.0 6 votes vote down vote up
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> unsortMap) {

    List<Map.Entry<K, V>> list =
      new LinkedList<Map.Entry<K, V>>(unsortMap.entrySet());

    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
      public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
        return (o2.getValue()).compareTo(o1.getValue());
      }
    });

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list) {
      result.put(entry.getKey(), entry.getValue());
    }

    return result;
  }
 
Example 13
Project: JSAT   Author: EdwardRaff   File: EigenValueDecomposition.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Sorts the eigen values and the corresponding eigenvector columns by the 
 * associated eigen value. Sorting can not occur if complex values are 
 * present. 
 * @param cmp the comparator to use to sort the eigen values
 */
public void sortByEigenValue(Comparator<Double> cmp)
{
    if(isComplex())
        throw new ArithmeticException("Eigen values can not be sorted due to complex results");
    IndexTable it = new IndexTable(DoubleList.unmodifiableView(d, d.length), cmp);
    
    for(int i = 0; i < d.length; i++)
    {
        RowColumnOps.swapCol(V, i, it.index(i));
        double tmp = d[i];
        d[i] = d[it.index(i)];
        d[it.index(i)] = tmp;
        
        it.swap(i, it.index(i));
    }
    
}
 
Example 14
Project: SONDY   Author: AdrienGuille   File: HashMapUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static <K, V extends Comparable<? super V>> Map<K, V> sortByDescValue( Map<K, V> map ){
    List<Map.Entry<K, V>> list =
        new LinkedList<>( map.entrySet() );
    Collections.sort( list, new Comparator<Map.Entry<K, V>>()
    {
        @Override
        public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 )
        {
            return -(o1.getValue()).compareTo( o2.getValue() );
        }
    } );

    Map<K, V> result = new LinkedHashMap<>();
    for (Map.Entry<K, V> entry : list)
    {
        result.put( entry.getKey(), entry.getValue() );
    }
    return result;
}
 
Example 15
Project: vjtools   Author: vipshop   File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sorts a Map by its values, using natural ordering.
 */
public static long[] sortAndFilterThreadIdsByValue(LongObjectMap map, int threadLimit) {
	int max = Math.min(threadLimit, map.size());
	List<Map.Entry> list = new LinkedList(map.entrySet());
	Collections.sort(list, new Comparator() {
		@Override
		public int compare(Object o1, Object o2) {
			return ((Comparable) ((Map.Entry) (o2)).getValue()).compareTo(((Map.Entry) (o1)).getValue());
		}
	});

	long[] topTidArray = new long[max];
	int i = 0;
	for (Map.Entry entry : list) {
		topTidArray[i] = (Long) entry.getKey();
		if (++i >= max) {
			break;
		}
	}

	return topTidArray;
}
 
Example 16
Project: spring-boot   Author: typa01   File: CollectionUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Map<String, Integer> sortMapByValueInt(Map<String, Integer> oriMap) {
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    if (oriMap != null && !oriMap.isEmpty()) {
        List<Map.Entry<String, Integer>> entryList = new ArrayList<Map.Entry<String, Integer>>(oriMap.entrySet());
        Collections.sort(entryList, (Map.Entry<String, Integer> entry1,
                                     Map.Entry<String, Integer> entry2) -> {
            int value1 = 0, value2 = 0;
            try {
                value1 = entry1.getValue();
                value2 = entry2.getValue();
            } catch (NumberFormatException e) {
                value1 = 0;
                value2 = 0;
            }
            return value2 - value1;
        });
        Iterator<Map.Entry<String, Integer>> iter = entryList.iterator();
        Map.Entry<String, Integer> tmpEntry = null;
        while (iter.hasNext()) {
            tmpEntry = iter.next();
            sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
        }
    }
    return sortedMap;
}
 
Example 17
Project: spring-boot   Author: typa01   File: CollectionUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Map按值排序
 */
public static Map<String, String> sortMapByValue(Map<String, String> oriMap) {
    Map<String, String> sortedMap = new LinkedHashMap<String, String>();
    if (oriMap != null && !oriMap.isEmpty()) {
        List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(oriMap.entrySet());
        Collections.sort(entryList, (Map.Entry<String, String> entry1,
                                     Map.Entry<String, String> entry2) -> {
            int value1 = 0, value2 = 0;
            try {
                value1 = getInt(entry1.getValue());
                value2 = getInt(entry2.getValue());
            } catch (NumberFormatException e) {
                value1 = 0;
                value2 = 0;
            }
            return value2 - value1;
        });
        Iterator<Map.Entry<String, String>> iter = entryList.iterator();
        Map.Entry<String, String> tmpEntry = null;
        while (iter.hasNext()) {
            tmpEntry = iter.next();
            sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
        }
    }
    return sortedMap;
}
 
Example 18
Project: agile-service-old   Author: choerodon   File: FieldValueServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<Long> sortIssueIdsByFieldValue(Long organizationId, Long projectId, PageRequest pageRequest) {
    if (pageRequest.getSort() != null) {
        Iterator<Sort.Order> iterator = pageRequest.getSort().iterator();
        String fieldCode = "";
        while (iterator.hasNext()) {
            Sort.Order order = iterator.next();
            fieldCode = order.getProperty();
        }
        ObjectSchemeFieldDTO objectSchemeField = objectSchemeFieldService.queryByFieldCode(organizationId, projectId, fieldCode);
        String fieldType = objectSchemeField.getFieldType();
        FieldValueUtil.handleAgileSortPageRequest(fieldCode, fieldType, pageRequest);
        return fieldValueMapper.sortIssueIdsByFieldValue(organizationId, projectId, objectSchemeField.getId(), PageUtil.sortToSql(pageRequest.getSort()));
    } else {
        return new ArrayList<>();
    }
}
 
Example 19
Project: vjtools   Author: DarLiner   File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sorts a Map by its values, using natural ordering.
 */
public static long[] sortAndFilterThreadIdsByValue(Map map, int threadLimit) {
	int max = Math.min(threadLimit, map.size());
	List<Map.Entry> list = new LinkedList(map.entrySet());
	Collections.sort(list, new Comparator() {
		@Override
		public int compare(Object o1, Object o2) {
			return ((Comparable) ((Map.Entry) (o2)).getValue()).compareTo(((Map.Entry) (o1)).getValue());
		}
	});

	long[] topTidArray = new long[max];
	int i = 0;
	for (Map.Entry entry : list) {
		topTidArray[i] = (Long) entry.getKey();
		if (++i >= max) {
			break;
		}
	}

	return topTidArray;
}
 
Example 20
Project: winter   Author: olehmberg   File: OtherOperations.java    License: Apache License 2.0 6 votes vote down vote up
@Deprecated
public <K, V extends Comparable<? super V>> Map<K, V> sortByValue(
		Map<K, V> map) {

	List<Map.Entry<K, V>> list = new LinkedList<Entry<K, V>>(
			map.entrySet());
	Collections.sort(list, new Comparator<Map.Entry<K, V>>() {

		public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
			return (o1.getValue()).compareTo(o2.getValue());
		}
	});

	Map<K, V> result = new LinkedHashMap<K, V>();
	for (Map.Entry<K, V> entry : list) {
		result.put(entry.getKey(), entry.getValue());
	}
	return result;
}
 
Example 21
Project: bluima   Author: BlueBrain   File: MapUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSortByValue() {
    Random random = new Random(System.currentTimeMillis());
    Map<String, Integer> testMap = new HashMap<String, Integer>(1000);
    for (int i = 0; i < 1000; ++i) {
        testMap.put("SomeString" + random.nextInt(), random.nextInt());
    }

    testMap = MapUtils.sortByValue(testMap);
    assertEquals(1000, testMap.size());

    Integer previous = null;
    for (Map.Entry<String, Integer> entry : testMap.entrySet()) {
        assertNotNull(entry.getValue());
        if (previous != null) {
            assertTrue(entry.getValue() >= previous);
        }
        previous = entry.getValue();
    }
}
 
Example 22
Project: StreamingRec   Author: mjugo   File: Util.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sorts the entries of a map based on their values
 * 
 * @param <K> - 
 * @param <V> - 
 * @param map -
 * @param ascending -
 * @return the sorted map
 */
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, final boolean ascending) {
	List<Map.Entry<K, V>> list = new ObjectArrayList<Map.Entry<K, V>>(map.entrySet());
	Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
		public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
			if (ascending) {
				return (o1.getValue()).compareTo(o2.getValue());
			} else {
				return (o2.getValue()).compareTo(o1.getValue());
			}

		}
	});

	Map<K, V> result = new Object2ObjectLinkedOpenHashMap<K, V>();
	for (Map.Entry<K, V> entry : list) {
		result.put(entry.getKey(), entry.getValue());
	}
	return result;
}
 
Example 23
Project: StreamingRec   Author: mjugo   File: Util.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sort the entries of a map based on their values and return the only the keys as a list
 * 
 * @param <K> - 
 * @param <V> - 
 * @param map -
 * @param ascending -
 * @param output -
 * @return a list of the key, sorted based on their values
 */
public static <K, V extends Comparable<? super V>> List<K> sortByValueAndGetKeys(Map<K, V> map,
		final boolean ascending, List<K> output) {
	List<Map.Entry<K, V>> list = new ObjectArrayList<Map.Entry<K, V>>(map.entrySet());
	Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
		public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
			if (ascending) {
				return (o1.getValue()).compareTo(o2.getValue());
			} else {
				return (o2.getValue()).compareTo(o1.getValue());
			}

		}
	});

	for (Map.Entry<K, V> entry : list) {
		output.add(entry.getKey());
	}
	return output;
}
 
Example 24
Project: systemds   Author: apache   File: SortUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
* In-place sort of two arrays, only indexes is used for comparison and values
* of same position are sorted accordingly. 
* 
   * @param start start index
   * @param end end index
   * @param values double array of values to sort
   * @param indexes int array of indexes to sort by
   */
  public static void sortByValueStable(int start, int end, double[] values, int[] indexes) 
  {    

  	sortByValue(start, end, values, indexes);
  	
  	// Maintain the stability of the index order.
for( int i=0; i<values.length-1; i++ ) {
	double tmp = values[i];
	//determine run of equal values
	int len = 0;
	while( i+len+1<values.length && tmp==values[i+len+1] )
		len++;
	//unstable sort of run indexes (equal value guaranteed)
	if( len>0 ) {
		Arrays.sort(indexes, i, i+len+1);
		i += len; //skip processed run
	}
}
  }
 
Example 25
Project: systemds   Author: apache   File: SortKeys.java    License: Apache License 2.0 6 votes vote down vote up
public static SortKeys constructSortByValueLop(Lop input1, Lop input2, OperationTypes op, 
		DataType dt, ValueType vt, ExecType et) {
	
	HashSet<Lop> set1 = new HashSet<>();
	set1.addAll(input1.getOutputs());
	// find intersection of input1.getOutputs() and input2.getOutputs();
	set1.retainAll(input2.getOutputs());
	
	for (Lop lop  : set1) {
		if ( lop.type == Lop.Type.SortKeys ) {
			return (SortKeys)lop;
		}
	}
	
	SortKeys retVal = new SortKeys(input1, input2, op, dt, vt, et);
	retVal.setAllPositions(input1.getFilename(), input1.getBeginLine(), input1.getBeginColumn(), input1.getEndLine(), input1.getEndColumn());
	return retVal;
}
 
Example 26
Project: ADW   Author: pilehvar   File: SemSigUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static <K, V extends Comparable<V>> Map<K, V> sortByValue(Map<K, V> map)
{
	Comparator<Map.Entry<K, V>> valueComparator = null;
	
	valueComparator = new Comparator<Map.Entry<K, V>>()
	{
		public int compare(Entry<K, V> o1, Entry<K, V> o2)
		{
			return o2.getValue().compareTo(o1.getValue());
		}
	};

	final List<Map.Entry<K, V>> entries = new LinkedList<Map.Entry<K, V>>(map.entrySet());

	Collections.sort(entries, valueComparator);
	
	final Map<K, V> result = new LinkedHashMap<K, V>();
	for (Map.Entry<K, V> entry : entries)
		result.put(entry.getKey(), entry.getValue());
	return result;
}
 
Example 27
Project: tassal   Author: mast-group   File: CollectionUtil.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Sort map by value (highest first) */
public static <K extends Comparable<K>, V extends Comparable<V>> Map<K, V> sortMapByValueDescending(
		final Map<K, V> map) {
	final Ordering<K> valueThenKeyComparator = Ordering.natural().reverse()
			.onResultOf(Functions.forMap(map))
			.compound(Ordering.<K> natural().reverse());
	return ImmutableSortedMap.copyOf(map, valueThenKeyComparator);
}
 
Example 28
/**
 * Tests sorting of data by value (ascending).
 */
@Test
public void testSortByValueAscending() {

    DefaultKeyedValues data = new DefaultKeyedValues();
    data.addValue("C", new Double(1.0));
    data.addValue("B", null);
    data.addValue("D", new Double(3.0));
    data.addValue("A", new Double(2.0));

    data.sortByValues(SortOrder.ASCENDING);

    // check key order
    assertEquals(data.getKey(0), "C");
    assertEquals(data.getKey(1), "A");
    assertEquals(data.getKey(2), "D");
    assertEquals(data.getKey(3), "B");

    // check retrieve value by key
    assertEquals(data.getValue("A"), new Double(2.0));
    assertEquals(data.getValue("B"), null);
    assertEquals(data.getValue("C"), new Double(1.0));
    assertEquals(data.getValue("D"), new Double(3.0));

    // check retrieve value by index
    assertEquals(data.getValue(0), new Double(1.0));
    assertEquals(data.getValue(1), new Double(2.0));
    assertEquals(data.getValue(2), new Double(3.0));
    assertEquals(data.getValue(3), null);

}
 
Example 29
Project: plugins   Author: open-osrs   File: CombatCounter.java    License: GNU General Public License v3.0 5 votes vote down vote up
private <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map)
{
	List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
	list.sort(Map.Entry.comparingByValue());

	Map<K, V> result = new LinkedHashMap<>();
	for (Map.Entry<K, V> entry : list)
	{
		result.put(entry.getKey(), entry.getValue());
	}

	return result;
}
 
Example 30
Project: pt2matsim   Author: matsim-org   File: MiscUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sorts a map by its values.
 *
 * @param unsortedMap the unsortedMap
 * @return the sorted map
 */
public static <K, V extends Comparable<V>> Map<K, V> sortMapAscendingByValue(Map<K, V> unsortedMap) {
	// Convert Map to List
	List<Map.Entry<K, V>> list = new LinkedList<>(unsortedMap.entrySet());

	// Sort list with comparator, to compare the Map values
	list.sort(Comparator.comparing(o -> (o.getValue())));

	// Convert sorted map back to a Map
	Map<K, V> sortedMap = new LinkedHashMap<>();
	for(Map.Entry<K, V> entry : list) {
		sortedMap.put(entry.getKey(), entry.getValue());
	}
	return sortedMap;
}
 
Example 31
Project: pt2matsim   Author: matsim-org   File: MiscUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sorts a map by its values.
 *
 * @param unsortedMap the unsortedMap
 * @return the sorted map
 */
public static <K, V extends Comparable<V>> Map<K, V> sortMapDescendingByValue(Map<K, V> unsortedMap) {
	// Convert Map to List
	List<Map.Entry<K, V>> list = new LinkedList<>(unsortedMap.entrySet());

	// Sort list with comparator, to compare the Map values
	list.sort((o1, o2) -> -(o1.getValue()).compareTo(o2.getValue()));

	// Convert sorted map back to a Map
	Map<K, V> sortedMap = new LinkedHashMap<>();
	for(Map.Entry<K, V> entry : list) {
		sortedMap.put(entry.getKey(), entry.getValue());
	}
	return sortedMap;
}
 
Example 32
/**
 * @param metricGroup the metric group to score
 * @return A score function to score by the metric group value of the given metric group in positive way, i.e. the higher
 *         the metric group value, the higher the score.
 */
public static Function<Replica, Double> sortByMetricGroupValue(String metricGroup) {
  return r -> {
    MetricValues metricValues = r.load()
                                 .loadByWindows()
                                 .valuesForGroup(metricGroup, KafkaMetricDef.commonMetricDef(), true);
    return (double) metricValues.avg();
  };
}
 
Example 33
Project: BPR   Author: AugustusYu   File: CommonUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sort the HashMap<K, V> by its values, from Large->Small.
 * @return List<Map.Entry<K, V>> with sorted entries.
 */
public static<K, V extends Comparable<? super V>> List<Map.Entry<K, V>> SortMapByValue(Map<K, V> map) {
	List<Map.Entry<K, V>> infoIds = new ArrayList<Map.Entry<K, V>>(map.entrySet()); 
	Comparator<Map.Entry<K, V>> c = new Comparator<Map.Entry<K, V>>() { 
		public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) { 
			return o2.getValue().compareTo(o1.getValue());
		}};
	Collections.sort(infoIds, c); 
	return infoIds;
}
 
Example 34
Project: pra   Author: noon99jaki   File: MapXX.java    License: MIT License 5 votes vote down vote up
public void KeyToVecSortByValue(VectorX<K> v) {
	v.clear();
	v.ensureCapacity(this.size());
	for (Map.Entry<V, VectorX<K>> e : ValueKeyToMapVec().entrySet())
		for (K k : e.getValue())
			v.add(k);
}
 
Example 35
Project: QuestionAnsweringSystem   Author: ysc   File: Tools.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 根据MAP的VALUE进行排序,升序
 *
 * @param map
 * @return
 */
public static <K> List<Map.Entry<K, Integer>> sortByIntegerValue(Map<K, Integer> map) {
    List<Map.Entry<K, Integer>> orderList = new ArrayList<>(map.entrySet());
    Collections.sort(orderList, new Comparator<Map.Entry<K, Integer>>() {
        @Override
        public int compare(Map.Entry<K, Integer> o1, Map.Entry<K, Integer> o2) {
            return (o1.getValue() - o2.getValue());
        }
    });
    return orderList;
}
 
Example 36
Project: secretshare   Author: timtiemens   File: SecretShare.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 *
 * @param map of key-value pairs
 * @return List - sorted by ASCENDING value
 */
private static <K extends Comparable<? super K>, V extends Comparable<? super V>>
               List<Map.Entry<K, V>> sortByValueAscendingThenKeyAscending(Map<K, V> map)
{
    List<Map.Entry<K, V>> list =
            new LinkedList<Map.Entry<K, V>>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<K, V>>()
    {
        @Override
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2)
        {
            int c = o1.getValue().compareTo(o2.getValue());
            if (c == 0)
            {
                c = o1.getKey().compareTo(o2.getKey());
            }
            return c;
        }
    });

    return list;
    //
    //Map<K, V> result = new LinkedHashMap<K, V>();
    //for (Map.Entry<K, V> entry : list)
    //{
    //    result.put( entry.getKey(), entry.getValue() );
    //}
    //return result;
}
 
Example 37
Project: ECG-Viewer   Author: CBLRIT   File: DefaultKeyedValuesTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Tests sorting of data by key (descending).
 */
@Test
public void testSortByValueDescending() {

    DefaultKeyedValues data = new DefaultKeyedValues();
    data.addValue("C", new Double(1.0));
    data.addValue("B", null);
    data.addValue("D", new Double(3.0));
    data.addValue("A", new Double(2.0));

    data.sortByValues(SortOrder.DESCENDING);

    // check key order
    assertEquals(data.getKey(0), "D");
    assertEquals(data.getKey(1), "A");
    assertEquals(data.getKey(2), "C");
    assertEquals(data.getKey(3), "B");

    // check retrieve value by key
    assertEquals(data.getValue("A"), new Double(2.0));
    assertEquals(data.getValue("B"), null);
    assertEquals(data.getValue("C"), new Double(1.0));
    assertEquals(data.getValue("D"), new Double(3.0));

    // check retrieve value by index
    assertEquals(data.getValue(0), new Double(3.0));
    assertEquals(data.getValue(1), new Double(2.0));
    assertEquals(data.getValue(2), new Double(1.0));
    assertEquals(data.getValue(3), null);

}
 
Example 38
Project: ECG-Viewer   Author: CBLRIT   File: DefaultKeyedValuesTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Tests sorting of data by value (ascending).
 */
@Test
public void testSortByValueAscending() {

    DefaultKeyedValues data = new DefaultKeyedValues();
    data.addValue("C", new Double(1.0));
    data.addValue("B", null);
    data.addValue("D", new Double(3.0));
    data.addValue("A", new Double(2.0));

    data.sortByValues(SortOrder.ASCENDING);

    // check key order
    assertEquals(data.getKey(0), "C");
    assertEquals(data.getKey(1), "A");
    assertEquals(data.getKey(2), "D");
    assertEquals(data.getKey(3), "B");

    // check retrieve value by key
    assertEquals(data.getValue("A"), new Double(2.0));
    assertEquals(data.getValue("B"), null);
    assertEquals(data.getValue("C"), new Double(1.0));
    assertEquals(data.getValue("D"), new Double(3.0));

    // check retrieve value by index
    assertEquals(data.getValue(0), new Double(1.0));
    assertEquals(data.getValue(1), new Double(2.0));
    assertEquals(data.getValue(2), new Double(3.0));
    assertEquals(data.getValue(3), null);

}
 
Example 39
Project: openstock   Author: lcmeyer37   File: DefaultKeyedValuesTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Tests sorting of data by value (ascending).
 */
@Test
public void testSortByValueAscending() {

    DefaultKeyedValues data = new DefaultKeyedValues();
    data.addValue("C", new Double(1.0));
    data.addValue("B", null);
    data.addValue("D", new Double(3.0));
    data.addValue("A", new Double(2.0));

    data.sortByValues(SortOrder.ASCENDING);

    // check key order
    assertEquals(data.getKey(0), "C");
    assertEquals(data.getKey(1), "A");
    assertEquals(data.getKey(2), "D");
    assertEquals(data.getKey(3), "B");

    // check retrieve value by key
    assertEquals(data.getValue("A"), new Double(2.0));
    assertEquals(data.getValue("B"), null);
    assertEquals(data.getValue("C"), new Double(1.0));
    assertEquals(data.getValue("D"), new Double(3.0));

    // check retrieve value by index
    assertEquals(data.getValue(0), new Double(1.0));
    assertEquals(data.getValue(1), new Double(2.0));
    assertEquals(data.getValue(2), new Double(3.0));
    assertEquals(data.getValue(3), null);

}
 
Example 40
Project: LAML   Author: MingjieQian   File: Utility.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sort a map by its values according to a specified order. The input map 
 * can be any map. One can cast the returned map to {@code HashMap} but 
 * not {@code TreeMap}.
 * 
 * @param <K> 
 *        Class type for the key in the map.
 *        
 * @param <V>
 *        Class type for the value in the map.
 *        
 * @param map
 *        The map to be sorted which can be {@code TreeMap} or {@code HashMap}.
 *        
 * @param order
 *        The {@code String} indicating the order by which the map
 *        to be sorted, either "descend" or "ascend".
 * @return
 *        A sorted map by a specified order.
 */
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(final Map<K, V> map, String order ) {  
	
	List<Map.Entry<K, V>> list =  new LinkedList<Map.Entry<K, V>>( map.entrySet() );   
	
	if ( order.compareTo("ascend") == 0 ) {
		Collections.sort( list, new Comparator<Map.Entry<K, V>>() {      
			public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 ) {       
				return (o1.getValue()).compareTo( o2.getValue() );      
			}    
		} );  
	} else if ( order.compareTo("descend") == 0 ) {
		Collections.sort( list, new Comparator<Map.Entry<K, V>>() {      
			public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 ) {       
				return (o2.getValue()).compareTo( o1.getValue() );      
			}    
		} ); 
	} else {
		System.err.println("order should be either \"descend\" or \"ascend\"!");
	}
	
	Map<K, V> result = new LinkedHashMap<K, V>();        
	for (Map.Entry<K, V> entry : list) {    
		result.put( entry.getKey(), entry.getValue() );   
	}
	
	return result;
}
 
Example 41
Project: rocketmq-all-4.1.0-incubating   Author: jiangxinlingdu   File: TestUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
            return (o1.getValue()).compareTo(o2.getValue());
        }
    });

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}
 
Example 42
Project: NFVO   Author: openbaton   File: VnfmManager.java    License: Apache License 2.0 5 votes vote down vote up
private static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
  List<Entry<K, V>> list = new LinkedList<>(map.entrySet());
  list.sort(Comparator.comparing(o -> (o.getValue())));

  Map<K, V> result = new LinkedHashMap<>();
  for (Entry<K, V> entry : list) {
    result.put(entry.getKey(), entry.getValue());
  }
  return result;
}
 
Example 43
Project: rocketmq   Author: JiangJibo   File: TestUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
            return (o1.getValue()).compareTo(o2.getValue());
        }
    });

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}
 
Example 44
Project: codehelper.generator   Author: zhengjunbase   File: IOUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static <K,  V extends Comparable > List<Map.Entry<K, V>> sortMapByValue(Map<K, V> map){
    List<Map.Entry<K, V>> entryList = Lists.newArrayList(map.entrySet());
    Collections.sort(entryList, new Comparator<Map.Entry<K, V>>() {
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
            return o1.getValue().compareTo(o2.getValue());
        }
    });
    return entryList;
}
 
Example 45
Project: lucene-solr   Author: apache   File: FeaturesSelectionStream.java    License: Apache License 2.0 5 votes vote down vote up
private  <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map )
{
  Map<K, V> result = new LinkedHashMap<>();
  Stream<Map.Entry<K, V>> st = map.entrySet().stream();

  st.sorted( Map.Entry.comparingByValue(
      (c1, c2) -> c2.compareTo(c1)
  ) ).forEachOrdered( e -> result.put(e.getKey(), e.getValue()) );

  return result;
}
 
Example 46
Project: buffer_bci   Author: jadref   File: DefaultKeyedValuesTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Tests sorting of data by key (descending).
 */
@Test
public void testSortByValueDescending() {

    DefaultKeyedValues data = new DefaultKeyedValues();
    data.addValue("C", new Double(1.0));
    data.addValue("B", null);
    data.addValue("D", new Double(3.0));
    data.addValue("A", new Double(2.0));

    data.sortByValues(SortOrder.DESCENDING);

    // check key order
    assertEquals(data.getKey(0), "D");
    assertEquals(data.getKey(1), "A");
    assertEquals(data.getKey(2), "C");
    assertEquals(data.getKey(3), "B");

    // check retrieve value by key
    assertEquals(data.getValue("A"), new Double(2.0));
    assertEquals(data.getValue("B"), null);
    assertEquals(data.getValue("C"), new Double(1.0));
    assertEquals(data.getValue("D"), new Double(3.0));

    // check retrieve value by index
    assertEquals(data.getValue(0), new Double(3.0));
    assertEquals(data.getValue(1), new Double(2.0));
    assertEquals(data.getValue(2), new Double(1.0));
    assertEquals(data.getValue(3), null);

}
 
Example 47
Project: JobX   Author: jobxhub   File: CommonUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValue(Map<K, V> map) {
    List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
            return (o1.getValue()).compareTo(o2.getValue());
        }
    });

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}
 
Example 48
Project: Eagle   Author: eBay   File: TimeSeriesPostFlatAggregateSort.java    License: Apache License 2.0 5 votes vote down vote up
private static SortedSet<Map.Entry<List<String>, List<Double>>> sortByValue(
		Map<List<String>, List<Double>> mapForSort,
		List<SortOption> sortOptions) {
	SortedSet<Map.Entry<List<String>, List<Double>>> sortedEntries = new TreeSet<Map.Entry<List<String>, List<Double>>>(
			new MapEntryComparator(sortOptions));
	sortedEntries.addAll(mapForSort.entrySet());
	return sortedEntries;
}
 
Example 49
private <K, V> Map<K, V> sortByValue(Map<K, V> map) {
    List list = new LinkedList(map.entrySet());
    Collections.sort(list, (Object object1, Object object2) -> ((Comparable) ((Map.Entry<K, V>) (object1)).getValue()).compareTo(
            ((Map.Entry<K, V>) (object2)).getValue()));
    Map<K, V> result = new LinkedHashMap<>();
    for (Iterator it = list.iterator(); it.hasNext();) {
        Map.Entry<K, V> entry = (Map.Entry<K, V>) it.next();
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}
 
Example 50
Project: ReactionDecoder   Author: asad   File: Sotter.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
public synchronized static Map<Integer, Double> sortMapByValueInAscendingOrder(Map<Integer, Double> map) {
    List<Map.Entry<Integer, Double>> list = new LinkedList<>(map.entrySet());
    // Sort the list using an annonymous inner class implementing Comparator for the compare method
    Collections.sort(list, (Map.Entry<Integer, Double> entry, Map.Entry<Integer, Double> entry1) -> (entry.getValue().equals(entry1.getValue()) ? 0 : (entry.getValue() > entry1.getValue() ? 1 : -1)) // Return 0 for eAtom match, -1 for less than and +1 for more then (Aceending Order Sort)
    );
    // LOGGER.info(list);
    Map<Integer, Double> result = new LinkedHashMap<>();
    list.stream().forEach((entry) -> {
        result.put(entry.getKey(), entry.getValue());
    });
    return result;
}
 
Example 51
Project: journaldev   Author: journaldev   File: MainActivity.java    License: MIT License 5 votes vote down vote up
public static HashMap<String, Integer> sortByValueDesc(Map<String, Integer> map) {
    List<Map.Entry<String, Integer>> list = new LinkedList(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
        @Override
        public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
            return o2.getValue().compareTo(o1.getValue());
        }
    });

    HashMap<String, Integer> result = new LinkedHashMap<>();
    for (Map.Entry<String, Integer> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}
 
Example 52
Project: api-mining   Author: mast-group   File: CollectionUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
/** Sort map by value (lowest first) */
public static <K extends Comparable<K>, V extends Comparable<V>> Map<K, V> sortMapByValueAscending(
		final Map<K, V> map) {
	final Ordering<K> valueThenKeyComparator = Ordering.natural()
			.onResultOf(Functions.forMap(map))
			.compound(Ordering.<K> natural());
	return ImmutableSortedMap.copyOf(map, valueThenKeyComparator);
}
 
Example 53
Project: api-mining   Author: mast-group   File: CollectionUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
/** Sort map by value (highest first) */
public static <K extends Comparable<K>, V extends Comparable<V>> Map<K, V> sortMapByValueDescending(
		final Map<K, V> map) {
	final Ordering<K> valueThenKeyComparator = Ordering.natural().reverse()
			.onResultOf(Functions.forMap(map))
			.compound(Ordering.<K> natural().reverse());
	return ImmutableSortedMap.copyOf(map, valueThenKeyComparator);
}
 
Example 54
Project: rocketmq-4.3.0   Author: tianheframe   File: TestUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
            return (o1.getValue()).compareTo(o2.getValue());
        }
    });

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}
 
Example 55
Project: xmnlp   Author: JoeWoo   File: CollectionUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * map 按照value排序
 *
 * @return
 */
public static <K, V> List<Map.Entry<K, V>> sortMapByValue(Map<K, V> map, final int sort) {
	List<Map.Entry<K, V>> orderList = new ArrayList<Map.Entry<K, V>>(map.entrySet());
	Collections.sort(orderList, new Comparator<Map.Entry<K, V>>() {
		@Override
		@SuppressWarnings("unchecked")
		public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
			return (((Comparable<V>) o2.getValue()).compareTo(o1.getValue())) * sort;
		}
	});
	return orderList;
}
 
Example 56
Project: vjtools   Author: DarLiner   File: MapUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static <K, V> Map<K, V> sortByValueInternal(Map<K, V> map, Comparator<Entry<K, V>> comparator) {
	Set<Entry<K, V>> entrySet = map.entrySet();
	Entry<K, V>[] entryArray = entrySet.toArray(new Entry[0]);

	Arrays.sort(entryArray, comparator);

	Map<K, V> result = new LinkedHashMap<K, V>();
	for (Entry<K, V> entry : entryArray) {
		result.put(entry.getKey(), entry.getValue());
	}
	return result;
}
 
Example 57
Project: Benchmark   Author: CityBench   File: MapUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
	List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
	Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
		public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
			return (o1.getValue()).compareTo(o2.getValue());
		}
	});

	Map<K, V> result = new LinkedHashMap<K, V>();
	for (Map.Entry<K, V> entry : list) {
		result.put(entry.getKey(), entry.getValue());
	}
	return result;
}
 
Example 58
Project: SIMVA-SoS   Author: SESoS   File: DefaultKeyedValuesTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests sorting of data by value (ascending).
 */
@Test
public void testSortByValueAscending() {

    DefaultKeyedValues data = new DefaultKeyedValues();
    data.addValue("C", new Double(1.0));
    data.addValue("B", null);
    data.addValue("D", new Double(3.0));
    data.addValue("A", new Double(2.0));

    data.sortByValues(SortOrder.ASCENDING);

    // check key order
    assertEquals(data.getKey(0), "C");
    assertEquals(data.getKey(1), "A");
    assertEquals(data.getKey(2), "D");
    assertEquals(data.getKey(3), "B");

    // check retrieve value by key
    assertEquals(data.getValue("A"), new Double(2.0));
    assertEquals(data.getValue("B"), null);
    assertEquals(data.getValue("C"), new Double(1.0));
    assertEquals(data.getValue("D"), new Double(3.0));

    // check retrieve value by index
    assertEquals(data.getValue(0), new Double(1.0));
    assertEquals(data.getValue(1), new Double(2.0));
    assertEquals(data.getValue(2), new Double(3.0));
    assertEquals(data.getValue(3), null);

}
 
Example 59
Project: ache   Author: VIDA-NYU   File: RelevanceModel.java    License: Apache License 2.0 5 votes vote down vote up
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueInDescendingOrder(Map<K, V> map) {
    List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
            return (o2.getValue()).compareTo(o1.getValue());
        }
    });

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}
 
Example 60
Project: bulbasaur   Author: alibaba   File: Bulbasaur.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 按值排序
 *
 * @param <K>
 * @param <V>
 * @param map
 * @return Map<K
                   *       ,
                   *       V>
 * @since 2012-12-5 下午2:19:38
 */
public static <K, V extends Comparable<V>> Map<K, V> sortByValue(Map<K, V> map) {
    List<Entry<K, V>> list = new LinkedList<Entry<K, V>>(map.entrySet());
    Collections.sort(list, new Comparator<Entry<K, V>>() {
        @Override
        public int compare(Entry<K, V> o2, Entry<K, V> o1) {

            Comparable<V> v1 = o1.getValue();
            V v2 = o2.getValue();
            if (v1 == null) {
                if (v2 == null) {
                    return 0;
                } else {
                    return -1;
                }
            } else {
                if (v2 == null) {
                    return 1;
                } else {
                    return v1.compareTo(v2);
                }
            }
        }
    });
    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Entry<K, V> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}