Tag: java collections api

使用Java 8集合流API进行堆栈

我有一个方法,每次执行它时都会生成一个对象,我需要颠倒我获取它们的顺序。 所以我认为这样做的自然方式是Stack,因为它是LIFO。 但是,Java Stack似乎不能与新的Java 8流API一起使用。 如果我这样做: Stack stack = new Stack(); stack.push(“A”); stack.push(“B”); stack.push(“C”); List list = stack.stream().collect(Collectors.toList()); System.out.println(“Collected: ” + list); 我得到的输出是: Collected: [A, B, C] 为什么不以预期的LIFO顺序将它们输出到流中? 这是将所有项目从堆栈清除到右(LIFO)订单列表的正确方法吗?

通过使用java 8流对集合进行排序,将集合转换为Map

我有一个列表,我需要先自定义它,然后将其转换为一个地图与它的Id vs name map。 这是代码,但是— Map map = new LinkedHashMap(); list.stream().sorted(Comparator.comparing(Building::getName)).forEach(b-> map.put(b.getId(), b.getName())); 我认为这将完成这项工作,但我想知道我是否可以避免在这里创建链接哈希映射,就像花哨的函数编程在一行中完成工作一样?

List中的contains()方法未按预期工作

contains()方法的api说 “如果此列表包含指定的元素,则返回true。更正式地,当且仅当此列表包含至少一个元素e时才返回true(o == null?e == null:o.equals(e))。” 我覆盖了我的类中的equals()方法,但是当我检查时, contains()仍然返回false 我的代码 class Animal implements Comparable{ int legs; Animal(int legs){this.legs=legs;} public int compareTo(Animal otherAnimal){ return this.legs-otherAnimal.legs; } public String toString(){return this.getClass().getName();} public boolean equals(Animal otherAnimal){ return (this.legs==otherAnimal.legs) && (this.getClass().getName().equals(otherAnimal.getClass().getName())); } public int hashCode(){ byte[] byteVal = this.getClass().getName().getBytes(); int sum=0; for(int i=0, n=byteVal.length; i<n ; i++) sum+=byteVal[i]; sum+=this.legs; return […]

按原始布尔类型对ArrayList进行排序

我想使用布尔类型对ArrayList进行排序。 基本上我想首先显示true条目。 这是我的代码如下: Abc.java public class Abc { int id; bool isClickable; Abc(int i, boolean isCl){ this.id = i; this.isClickable = iCl; } } Main.java List abc = new ArrayList(); //add entries here //now sort them Collections.sort(abc, new Comparator(){ @Override public int compare(Abc abc1, Abc abc2){ boolean b1 = abc1.isClickable; boolean b2 = abc2.isClickable; if […]

为什么jdk代码样式使用变量赋值并在同一行读取 – 例如。 (i = 2)<max

我注意到在jdk源代码中,更具体地说,在集合框架中,在表达式中读取变量之前,首先要分配变量。 这只是一个简单的偏好还是更重要的我不知道的东西? 我能想到的一个原因是该变量仅在此表达式中使用。 由于我不习惯这种风格,我发现很难读懂它。 代码非常简洁。 您可以在下面看到从java.util.HashMap.getNode()获取的示例 Node[] tab; Node first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && …) { … }